Java抽象类计算体积


abstract class Geometr //定义抽象类,几何图形
{
public abstract double getArea(); //抽象函数,得到底面积
}

class Pillar //柱子类 
{
Geometr bottom; //柱子的底面
double height; //柱子的高
Pillar(Geometr bottom,double height) //柱子的构造函数,两个参数,一个是底,一个是高
{
this.bottom=bottom; //形参的bottom给私有变量的bottom初始化
this.height=height; //形参的height给私有变量的height初始化
}
public double getVolume() //求体积
{
if(bottom==null) //判断底面积是否为空
{
System.out.println("没有底,无法计算!");
return -1;
}
return bottom.getArea()*height; //有底面积和高,就返回体积
}
}

class Circle extends Geometr //圆类继承几何图形
{
double r;
Circle(double rr) //圆的构造函数
{
r=rr;
}
public double getArea() //抽象函数的实例化
{
return 3.14*r*r; //返回圆柱底面积
}
}

class Rectangle extends Geometr //长方体继承几何图形
{
double a,b;
Rectangle(double aa,double bb) //长方面形构造函数
{
a=aa;
b=bb;
}
public double getArea() //实例化抽象函数
{
return a*b; //返回四棱柱底面积
}
}

public class geometry {
public static void main(String []args) //主函数
{
Pillar pillar; //柱子类,声明一个对象
Geometr bottom=null;
pillar=new Pillar(bottom,100);
System.out.println("体积:"+pillar.getVolume());

bottom=new Rectangle(12,22);
pillar=new Pillar(bottom,58);
System.out.println("体积:"+pillar.getVolume());

bottom=new Circle(10);
pillar=new Pillar(bottom,58);
System.out.println("体积:"+pillar.getVolume());
}
}

运行结果:

 

posted @ 2020-12-08 21:24  bobo哥  阅读(440)  评论(0编辑  收藏  举报