先上代碼:
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訪問類的私有成員變量是可以的,並不違反封裝原則。
運行結果截圖: