设计一个形状类(接口)Shape,方法:求周长和求面积
形状类(接口)的子类(实现类):
Rect(矩形)
Circle(圆形)
/*
* 设计一个形状类(接口)Shape,方法:求周长和求面积
* */
public interface Shape {
double perimeter();//周长
double area();//面积
}
public class Rect implements Shape {
private double height;//高
private double wide;//宽
@Override
public double area(){
return wide * height;
}
@Override
public double perimeter(){
return 2*(wide + height);
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double getWide() {
return wide;
}
public void setWide(double wide) {
this.wide = wide;
}
public Rect(double height, double wide) {
this.height = height;
this.wide = wide;
}
public Rect(double wide) {
this.wide = wide;
}
}
public class Circle implements Shape{
private final double a=3.14;//圆周率
private double radius;//半径
@Override
public double perimeter(){
return 2*a*radius;
}
@Override
public double area(){
return a*radius*radius;
}
public double getA() {
return a;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
public Circle(double radius) {
this.radius = radius;
}
public Circle() {
}
}
Rect类的子类:
Square(正方形)
public class Square extends Rect{
@Override
public double area(){
return getWide() * getWide();
}
@Override
public double perimeter(){
return 4*getWide();
}
public Square(double height, double wide) {
super(height, wide);
}
public Square(double wide) {
super(wide);
}
}
public class Test {
public static void main(String[] args) {
Shape[] shapes = new Shape[3];
shapes[0]=new Circle(2);
shapes[1]=new Rect(3,8);
shapes[2]=new Square(7);
System.out.println("圆,矩形,正方体");
for (int i = 0; i < shapes.length; i++) {
System.out.println(""+"面积为"+shapes[i].area()+"周长为"+shapes[i].perimeter());
}
}
}
运行结果
圆,矩形,正方体
面积为12.56周长为12.56
面积为24.0周长为22.0
面积为49.0周长为28.0
Process finished with exit code 0