public interface Shape {
public double area(); //计算面积
public double perimeter(); //计算周长
}
class Square implements Shape {
double a; //边长
public Square(double a) {
this.a = a;
}
public double area() {
return a*a;
}
public double perimeter() {
return 4*a;
}
}
class Rectangle implements Shape {
double a; //长或宽
double b; //长或宽
public Rectangle(double a, double b) {
this.a = a;
this.b = b;
}
public double area() {
return a*b;
}
public double perimeter() {
return 2*(a+b);
}
}
class Circle implements Shape {
double radius; //半径
public Circle(double radius) {
this.radius = radius;
}
public double area() {
return Math.PI*radius*radius;
}
public double perimeter() {
return 2*Math.PI*radius;
}
}
public class ShapeTest {
public static void print(Shape shape){
System.out.println(shape.getClass()+":"+"面积:"+shape.area());
System.out.println(shape.getClass()+":"+"周长:"+shape.perimeter());
}
public static void main(String[] args) {
Shape shape=new Rectangle(4,5);
print(shape);
shape=new Circle(4);
print(shape);
shape=new Square(5);
print(shape);
}
}