编程实现:设计平面图形的类PGraphic,其中包含计算面积的方法area(). 现有矩形(PRectangle)和圆(Circle)两种平面图形,利用抽象类可以派生子类的特性,求其面积,
1. 平面图形的类PGraphic,其中包含计算面积的方法area().
public abstract class PGraphic {
public abstract double area();
}
2. 圆(Circle)类,继承PGraphic类
public class PCircle extends PGraphic{
double r;
public PCircle(double r) {
this.r=r;
}
public double area() {
return Math.PI*r*r;
}
}
3. 矩形(PRectangle)类,继承PGraphic类
public class PRectangle extends PGraphic {
//定义长、宽
double l;
double d;
public PRectangle(double l,double d) {
this.l=l;
this.d=d;
}
public double area() {
return l*d;
}
}
4. 测试类PGraphicTest
public class PGraphicTest {
public static void main(String[] args) {
PGraphic p=new PRectangle(3,4);//上转变换,p上转型变量
//PRectangle p1=new PRectangle(3,4);
System.out.printf("矩形的面积为:%.2f\n",p.area());
p=new PCircle(10);
//PCircle p2=new PCircle(10);
System.out.printf("矩形的面积为:%.2f\n",p.area());
}
}