java声明一个接口Shape2D用来实现二维几何形状类Circle和Rectangle。10
匿名网友2015.05.20浏览371次分享举报
1、声明一个接口Shape2D用来实现二维几何形状类Circle和Rectangle。要把计算面积和周长的方法声明在接口里,同时声明常量PI。然后声明Circle类和Rectangle类分别计算圆面积和矩形面积,实现Shape2D。
2、在main()方法中用定义两个Shape2D类型的引用,一个指向Circle的对象,另一个指向Rectangle的对象,再用这两个引用去调用Circle对象和Rectangle对象的求周长和面积的方法。
public interface Shape2D {
double PI=3.14;
public abstract double area();
public abstract double perimeter();
}
public class Circle implements Shape2D{
double r;
public Circle(double r)//构造方法
{
this.r = r;
}
public double area() {
return PI*r*r;
}
public double perimeter() {
return 2*PI*r;
}
}
public class Rectangle implements Shape2D {
protected double length, width;
public Rectangle(double length, double width)
{
this.length = length;
this.width = width;
}
public double area()
{
return this.width * this.length;
}
public double perimeter()
{
return (this.width+this.length)*2;
}
}
public class Test {
public static void main(String[] args) {
Shape2D yuan = new Circle(1);
Shape2D ju = new Rectangle(4, 5);
yuan.area();
yuan.perimeter();
ju.area();
ju.perimeter();
}
}
哪里有问题?