一直以为私有变量就是任何地方(除了类里面访问当前对象的private字段)都访问不到的,原来在类自身里面是可以访问其他该类对象的私有变量的,有点绕,看代码吧。
class TestPrivate2 {
private int n;
}
public class TestPrivate {
private int n;
public void accessOtherPrivate(TestPrivate other) {
other.n = 10;//这里是可以访问同类型的其他对象other的private字段的
System.out.println(other.n);
}
public void accessOtherPrivate(TestPrivate2 other) {
// other.n = 10;//编译错误
// System.out.println(other.n);//编译错误
}
public static void main(String[] args) {
new TestPrivate().accessOtherPrivate(new TestPrivate());
}
}
这个是今天看《快学Scala》里看到Scala里面是有private[this] var field这样的“对象私有变量”的。