以下代码可以完美运行。
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)));
}
}
现在根据面向对象的设计模型,不应通过对象引用访问私有(private)实例成员(c1.real 已在此处完成)。
因此,从这个意义上说,应该存在编译器错误。但它并不反对。
现在根据我的理解这是允许的因为
c1.real代码写在私有(private)类Complex类本身的主体中。
Complex 类的开发人员在通过对象引用访问时应该有权访问所有实例成员 [无论是私有(private)的还是 protected ],因为与任何第三方不同,开发人员非常清楚自己在做什么。这就是为什么这里不遵循面向对象模型的原因。
谁能就为什么允许 c1.real 代码在这里提出更好的解释?
最佳答案
private 意味着它不能从另一个外部类访问。它是基于类的,而不是基于对象的安全性。注意:同一外部类中的类可以访问该文件中任何其他类的私有(private)成员。
http://vanillajava.blogspot.co.uk/2012/02/outer-class-local-access.html
关于java - java中private关键字的含义是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9955262/