Shape
public abstract class Shape {
private double area;
private double per;
private String color;
public Shape() {
}
public Shape(String color) {
this.color = color;
}
public abstract double getArea();
public abstract double getPer();
public abstract void showAll();
}
Rectangle
public class Rectangle extends Shape {
private double width;
private double height;
public Rectangle() {
}
public Rectangle(double width, double height, String color) {
super(color);
this.width = width;
this.height = height;
}
@Override
public double getArea() {
return width * height;
}
@Override
public double getPer() {
return 2 * (width + height);
}
@Override
public void showAll() {
System.out.println("矩形");
System.out.println("长:" + '\t' + width);
System.out.println("宽:" + '\t' + height);
System.out.println("面积:" + '\t' + getArea());
System.out.println("周长:" + '\t' + getPer());
System.out.println("--------------------");
}
}
Circle
public class Circle extends Shape {
private double radius;
public Circle() {
}
public Circle(double radius, String color) {
super(color);
this.radius = radius;
}
@Override
public double getArea() {
return 3.14 * radius * radius;
}
@Override
public double getPer() {
return 2 * 3.14 * radius;
}
@Override
public void showAll() {
System.out.println("圆");
System.out.println("半径:" + '\t' + radius);
System.out.println("面积:" + '\t' + getArea());
System.out.println("周长:" + '\t' + getPer());
}
}
Test
public class Test {
public static void main(String[] args) {
Shape[] shape = new Shape[2];
Rectangle rectangle = new Rectangle(1, 2, "蓝色");
Circle circle = new Circle(1.2, "红色");
shape[0] = rectangle;
shape[1] = circle;
for (Shape shape2 : shape) {
shape2.showAll();
}
}
}