我仍然是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