利用JAVA中关于继承的相关知识求得圆柱体体积并输出
Write a program:
1)Define a Circle class and a Cylinder class, which is derived from the Circle and is the main class.
2)Circle class has one field: radius r, which are initialized through Circle’s constructor; one method getArea() to get the area of circle.
3)Cylinder class has one field: h, which is initialized through Cylinder’s constructor. one method getVolume() to get the of volume of cylinder.
4)In main method: output the volume of cylinder.
写程序计算圆柱体的体积:
要求:
① 定义Circle类:成员变量包括半径r,成员方法包括构造方法来初始化成员变量r,以及getArea方法用来计算面积;
② 定义Cylinder类:成员变量包括底面积(用Circle类继承得到)和高,成员方法包括构造方法来初始化成员变量(包括半径r和高h的初始化),getVolme方法用来计算圆柱体积;
③ Cylinder类作为主类,在Main方法中创建Cylinder类的对象,求得圆柱体体积并输出.、
class Circle{
double r;
public Circle(double r) {
this.r=r;
}
public double getArea() {
double area;
area=3.14*r*r;
return area;
}
}
class Cylinder extends Circle{
double height;
double Area=getArea();
public Cylinder(double r,double height) {
super(r);
this.height=height;
}
public double getVolme() {
double v;
v=Area*height;
return v;
}
public static void main(String[] args) {
Cylinder hh=new Cylinder(100,10);
System.out.println("圆柱体体积"+hh.getVolme());
}
}
运行结果: