先上代码:
package yerasel;
public class MyTest {
private int i;
public MyTest(int x) {
this.i = x;
}
public void getI() {
System.out.println("Get from public method: " + this.i);
}
public void setI(int x) {
MyTest innerObj = new MyTest(x);
System.out.println("Get private param from method: " + innerObj.i);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
MyTest my = new MyTest(1);
my.setI(10);
my.getI();
}
}
看起来,直接innerObj.i是不行的,但是跟this.i比比,是不是几乎一样呢?
在类的共有方法内获得innerObj对象,然后通过innerObj.i访问类的私有成员变量是可以的,并不违反封装原则。
运行结果截图: