为什么我可以调用私有方法?
发布于 2021-01-30 17:32:20
我不应该能够调用实例化对象的私有方法。我想知道为什么下面的代码有效。
public class SimpleApp2 {
/**
* @param args
*/
private int var1;
public static void main(String[] args) {
SimpleApp2 s = new SimpleApp2();
s.method1(); // interesting?!
}
private void method1() {
System.out.println("this is method1");
this.method2(); // this is ok
SimpleApp2 s2 = new SimpleApp2();
s2.method2(); // interesting?!
System.out.println(s2.var1); // interesting?!
}
private void method2() {
this.var1 = 10;
System.out.println("this is method2");
}
}
我知道可以从类中访问私有方法。但是,如果类中的方法实例化了同一类的对象,则作用域规则是否不适用于该实例化的对象?
如本例所示,像main这样的静态方法可以访问类的非静态成员吗?
关注者
0
被浏览
102
1 个回答