一共需要四个类,一个是A接口类,Circle 和 Rectangle 类,以及主Test
interface A{
public double getArea();
public double getPerimeter();
public double showArea();
public double showPerimeter();
}
public class Circle{
public void fun(A a){
a.getArea();
a.getPerimeter();
a.showArea();
a.showPerimeter();
}
}
public class Rectangle {
public void fun(A a){
a.getArea();
a.getPerimeter();
a.showArea();
a.showPerimeter();
}
}
public class Test{
public static void main(String[] args){
Rectangle rectangle=new Rectangle();
Circle circle=new Circle();
circle.fun(new A(){
double s,p;//面积,周长
double r=3;//半径
public double getArea(){
s=3.14*r*r;
return s;
}
public double getPerimeter(){
p=2*3.14*r;
return p;
}
public double showArea(){
System.out.println("圆的面积为:"+s);
return 0;
}
public double showPerimeter(){
System.out.println("圆的周长为:"+p);
return 0;
}
});
rectangle.fun(new A(){
double s,p;//面积,周长
double l=5,w=3;//长,宽
public double getArea(){
s=l*w;
return s;
}
public double getPerimeter(){
p=2*(l+w);
return p;
}
public double showArea(){
System.out.println("矩形的面积为:"+s);
return 0;
}
public double showPerimeter(){
System.out.println("矩形的周长为:"+p);
return 0;
}
});
}
}