我仍然是Java中的新手。我的问题可能是非常基本的。定义为Private的变量
我有一个类的超类箱,
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是框超类的子类:
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
}
}
高度和深度被定义为Private,所以实际传递这些变量的值的DemoBoxWeight不是abl e访问它。我知道我可以将Private改为default/public,但是还有另一种方式,以便传递值的类实际上可以访问它?
PS:由于我是新的我的术语可能是错误的,我的问题很愚蠢
基本上,你会想要使用getters和setter;公共方法来获取或修改您的私有变量。 – 2013-04-28 17:34:11
http://stackoverflow.com/questions/2036970/tutorial-on-getters-and-setters – 2013-04-28 17:34:18
你需要回答的第一个问题是,如果DemoBoxWeight能够访问高度和重量,或者是那些太接近实现细节应该隐藏其他类吗?如果它们应该可用,那么'public int getHeight()'会使高度可读。 – 2013-04-28 17:36:57