练习:
1.设计一个表示二维平面上点的类Point,包含有表示坐标位置的protected 类型的成员变量x 和y,获取和设置x 和y 值的public 方法。
2.设计一个表示二维平面上圆的类Circle,它继承自类Point,还包含有表示圆半径的protected 类型的成员变量r、获取和设置r 值的public 方法、计算圆面积的public 方法。
3.设计一个表示圆柱体的类Cylinder,它继承自类Circle,还包含有表示圆柱体高的protected 类型的成员变量h、获取和设置h 值的public 方法、计算圆柱体体积的public方法。
4.建立Cylinder 对象,输出其轴心位置坐标、半径、面积、高及其体积的值。
package com.company;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Cylinder cld=new Cylinder();
cld.Set();
System.out.print("轴心坐标为("+cld.x+","+cld.y+")半径为"+cld.r+",底面积为"+cld.getArea()+"高为"+cld.h+"体积为"+cld.getVolume());
}
}
//父类
class Point{
protected float x;
protected float y;
public void Set(){ //设置x,y
this.x=2.15f;
this.y=3.75f;
}
public float getX(){//获取x
return x; }
public float getY(){//获取y
return y; }
}
class Circle extends Point{
protected float r;
public void Set(){//设置半径
super.Set();
this.r=1.51f; }
public float getR() {
return r; }
public double getArea(){ //面积为double类型防止精度损失
return 3.14*r*r;
}
}
class Cylinder extends Circle{
protected float h;
public void Set() {
super.Set();
this.h=4.56f; }
public float getH() {
return h; }
public double getVolume() {
return super.getArea()*h;
}
}