我跑到下面的代码:私有变量初始化
public class Box {
private int length = 1;
private int width = 2;
private int height = 3;
Box(int l, int w, int h) {
length = l;
width = w;
height = h;
}
double volume() {
return length * width * height;
}
}
public class DemoBox {
public static void main(String[] args) {
Box box1 = new Box(3, 3, 3);
System.out.println("Volumne: " +box1.volume());
}
}
我一直以为我将无法修改私有变量的值,而无需的getter/setter。但在上面的代码中,我能够将值传递给私有变量,结果体积为27(3 * 3 * 3)。这是预期的行为,并请解释我失去了我在私人变数和getter/setter
回去再读一下私人变量。你可以在他们声明的类中访问它们。 'volume()'是'Box'的一个实例方法,因此可以访问它们。 – 2013-04-29 19:19:12
您只能像这样分配私有变量。获取者/设置者通常由于访问其他类而被定义为public。 – 2013-04-29 19:21:27