//创建圆的类
public class round {
protected double radius;
protected double area;
public void setRadius(double radius) { //设置圆的半径
this.radius = radius;
}
public double getArea() { //求圆的面积
return 3.14*radius*radius;
}
}
//创建继承自圆的圆柱体类
public class cylindrical extends round{
private double height;
private double voluem;
public void setHeight(double height){ //设置圆柱体的高
this.height = height;
}
public double getVoluem() { //求圆柱体的体积,半径继承自圆的类,不用重复定义
return 3.14*radius*radius*height;
}
}
//主函数类(测试类):
public class testMain {
public static void main(String[] args){
round round1 = new round();
cylindrical cylindrical1 = new cylindrical();
int n1;//定义一个整型数n1
BufferedReader distream = new BufferedReader(new InputStreamReader(System.in));
System.out.println( "请输入圆的半径:");
n1=Integer.parseInt(distream.readLine());//进行输入,并把输入的数存入n1中
round1.setRadius(n1); //假定输入为2.0
System.out.println("半径为"+n1+"时,圆的面积为:"+round1.getArea());
round1.setRadius(1.0);//注意,此时用到的对象是圆的对象,非圆柱体对
//象,所以圆柱体半径为零,下面输出结果也为0
cylindrical1.setHeight(1.0);
System.out.println("高为1,半径为1的圆柱体的体积为:"+cylindrical1.getVoluem());
cylindrical1.setRadius(1.0);
System.out.println("半径为1时圆的面积为:"+round1.getArea());
System.out.println("此时的圆柱体体积为:"+cylindrical1.getVoluem());
}
}
输出结果:
请输入圆的半径:2.0
半径为2时,圆的面积为:12.56
高为1,半径为1的圆柱体的体积为:0.0
半径为1时圆的面积为:3.14
此时的圆柱体体积为:3.14