Can one object access a private variable?

来源:互联网 发布:linux 内核启动参数 编辑:程序博客网 时间:2024/06/16 23:46
Q. Can one object access a private variable of another object of the same class?
A:
Yes! One object can access a private variable of another object of the same class. The private field can be accessed from static method of the class through an instance of the same class too.
Here is an example:
//****************
public class Test1 {
private int i;
Test1(int ii) {
i = ii;
System.out.println("Self: " + i);
// to avoid infinite recursion
if (i != 3) {
Test1 other = new Test1(3);
other.i++;
System.out.println("Other: " + other.i);
}
}
public static void main(String[] args) {
Test1 t = new Test1(5);
// The private field can be accessed from
// static method of the same class
// through an instance of the same class
System.out.println(t.i);
}
}
//****************
原创粉丝点击