类的抽象与封装
Posted 蜂蜜峰峰
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了类的抽象与封装相关的知识,希望对你有一定的参考价值。
package 圆;
public class circle {
private double Radius;
public double getRadius(){
return Radius;
};
public void setRadius(double r) {
Radius= r;
}
public circle(double r){
Radius=r;
}
public double getPerimeter(){//底圆周长
return 2 * Math.PI * Radius;
}
public double getArea(){//面积
return Math.PI *Radius *Radius;
}
public void show( ){
System.out.println("圆的半径: " +getRadius());
System.out.println("圆的面积: " +getArea());
System.out.println("圆的周长: " +getPerimeter());
}
}
package 圆;
public class yuanzhu extends circle {//圆柱类继承圆类
private double height;
public double getheight() {
return height;
}
public void setheight(double h) {
height = h;
}
public yuanzhu(double r,double h){
super(r);//引用父类同名成员变量
height=h;
}
public double getVolume(){//得到体积
return getArea() * height;
}
public void showVolume( ){
System.out.println("圆柱体的体积:" +getVolume());
}
}
package 圆;
public class MAIN {
public static void main(String[] args) {
circle d1 = new circle(2);//半径初始化为3
d1.show( );
yuanzhu d2 =new yuanzhu(3,6);//高初始化为6
d2.showVolume();
}
}
结果:圆的半径: 3.0
圆的面积: 28.274333882308138
圆的周长: 18.84955592153876
圆柱体的体积:169.64600329384882
以上是关于类的抽象与封装的主要内容,如果未能解决你的问题,请参考以下文章