【发布时间】:2012-03-31 10:54:27
【问题描述】:
以下代码可以完美运行。
public class Complex {
private int real, imag;
Complex(int r, int i) {
real = r;
imag = i;
}
public static Complex add(Complex c1, Complex c2) {
return new Complex(c1.real + c2.real, c1.imag + c2.imag);
}
public String toString() {
return real + "+i" + imag;
}
public static void main(String[] args) {
Integer.parseInt("5");
System.out.println(Complex.add(new Complex(2, 3), new Complex(3, 4)));
}
}
现在根据面向对象的设计模型,不应通过对象引用访问私有实例成员(此处已由 c1.real 完成)。
所以,从这个意义上说,应该存在编译器错误。但它不反对。
现在根据我的理解是允许的,因为
c1.real 代码写在私有类Complex 类本身的主体中。
Complex 类的开发人员在通过对象引用访问时应该有权访问所有实例成员 [无论是私有的还是受保护的],因为与任何第三方不同,开发人员非常清楚自己在做什么。这就是为什么这里没有遵循面向对象模型的原因。
谁能更好地解释一下为什么这里允许使用 c1.real 代码?
【问题讨论】:
-
“不能通过对象引用访问私有实例成员”——这是从哪里来的?
-
private/protected 的想法是对外界隐藏内部。一个类知道它自己并没有错。毕竟是同一个班级。
-
这种误解从何而来? => '面向对象的设计模型,不能通过对象引用访问私有实例成员'
-
+1 表示一个措辞良好的问题。
标签: java compiler-construction jvm private-members object-oriented-analysis