Java 类继承和访问修饰符:Circle 和 Cylinder 示例
Java 类继承和访问修饰符:Circle 和 Cylinder 示例
class Circle {
// 定义父类 - 圆类
private double radius; // 成员变量 - 圆半径
Circle() {
// 构造方法
radius = 0.0;
}
Circle(double r) {
// 构造方法
radius = r;
}
double getPerimeter() {
// 成员方法 - 求圆周长
return 2 * Math.PI * radius;
}
double getArea() {
// 成员方法 - 求圆面积
return Math.PI * radius * radius;
}
void disp() {
// 成员方法 - 显示圆半径、周长、面积
System.out.println('圆半径=' + radius);
System.out.println('圆周长=' + getPerimeter());
System.out.println('圆面积=' + getArea());
}
}
class Cylinder extends Circle {
// 定义子类 - 圆柱类
private double hight; // 成员变量 - 圆柱高
Cylinder(double r, double h) {
// 构造方法
super(r);
hight = h;
}
public double getVol() {
// 成员方法 - 求圆柱体积
return getArea() * hight;
}
public void dispVol() {
// 成员方法 - 显示圆柱体积
System.out.println('圆柱体积=' + getVol());
}
}
为什么 Circle 的成员函数前没有 public 而 Cylinder 的成员函数中有内容:public 关键字?
在 Java 中,如果没有指定访问修饰符,成员变量和成员方法默认为包级私有(即只能在同一个包中访问)。在上述代码中,Circle 类和 Cylinder 类都在同一个包中,因此 Circle 类中的成员方法可以被 Cylinder 类继承和访问。而 Cylinder 类的成员方法需要被其他类访问,因此需要使用 public 关键字进行修饰。
原文地址: https://www.cveoy.top/t/topic/oV3l 著作权归作者所有。请勿转载和采集!