我仍然是Java的新手。我的问题可能非常基本。
我有一个类超类Box,
package chapter8;
public class Box {
double width;
private double height;
private double depth;
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
double volume() {
return width * height * depth;
}
}
BoxWeight 是 Box 超类的子类:
package chapter8;
public class BoxWeight extends Box {
double weight;
BoxWeight(double w, double h, double d, double m){
super(w, h, d);
weight = m;
}
}
现在我主要在 DemoBoxWeight
package chapter8;
public class DemoBoxWeight {
public static void main(String[] args) {
BoxWeight myBox1 = new BoxWeight(2, 3, 4, 5);
System.out.println("Volume1 :" + myBox1.volume());
System.out.println("Weight1 :" + myBox1.weight);
System.out.println("Widht1: " + myBox1.width);
System.out.println("Depth1: " + myBox1.depth); // as depth is private, it is not accessible
}
}
由于高度和深度被定义为私有,因此实际传递这些变量的值的 DemoBoxWeight 无法访问它。我知道我可以将 Private 更改为默认/公共,但是还有另一种方法可以让传递值的类实际上可以访问它吗?
PS:因为我是新手,所以我的术语可能是错误的,我的问题真的很愚蠢