Java關於方法內調用private變量的問題

先上代碼:

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訪問類的私有成員變量是可以的,並不違反封裝原則。

運行結果截圖:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章