类的抽象与封装
Posted 卓摸卟透
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了类的抽象与封装相关的知识,希望对你有一定的参考价值。
//圆类
package lx;
public class Circle {
private double Radius;//存放圆的半径
public double getRadius() {//获取圆的半径
return Radius;
}
public void setRadius(double radius) {//设定半径
Radius = radius;
}
public Circle( ){//无参构造函数,将半径设为0
this.Radius=0;
}
public Circle(double r){//带参构造函数,将半径初始化为r
this.Radius = r;
}
public double getArea(double r){//获取圆的面积
return 3.14159 * r * r;
}
public double getPerimeter(double r){//获取圆的周长
return 2 * 3.14159* r;
}
public void show( ){
System.out.println("圆的面积: " + this.getArea(Radius));
System.out.println("圆的周长: " + this.getPerimeter(Radius));
}
}
//圆柱类
public class Cylinder extends Circle {//在圆的基础上定义一个圆柱
private double hight;
public Cylinder (double r, double h ){
super(r);
this.hight = h;
}
public double getVolume(){//求圆柱的体积
return 3.14159 * this.getRadius() * this.getRadius() * hight;
}
public void showVolume( ){
System.out.println("圆柱体的体积:" + this.getVolume());
}
}
public class Test {
public static void main(String[] args) {
Circle cc = new Circle();
cc.show( );
Cylinder ccc =new Cylinder(3, 6);//圆柱的底面圆的半径和和圆柱的高
ccc.showVolume();
}
}
以上是关于类的抽象与封装的主要内容,如果未能解决你的问题,请参考以下文章