Notice
Recent Posts
Recent Comments
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
관리 메뉴

충분히 쌓여가는

9.5 바깥 멤버 접근 - this 본문

이것이 자바다/09 중첩 선언과 익명 객체

9.5 바깥 멤버 접근 - this

빌드이너프 2024. 4. 4. 14:50

중첩 클래스 내부에서 this는 해당 중첩 클래스의 객체를 말한다

만약 중첩 클래스 내부에서 바깥 클래스의 객체를 얻으려면 바깥 클래스 이름에 this를 붙여주면 된다

package ch09.sec05.exam02;

public class A {
	String field = "A-field";
	
	void method() {
		System.out.println("A-method");
	}
	
	class B {
		String field = "B-field";
		
		void method() {
			System.out.println("B-method");
		}
		
		void print() {
			//B 객체의 필드와 메소드 사용
			System.out.println(this.field);
			this.method();
			
			//A 객체의 필드와 메소드 사용
			System.out.println(A.this.field);
			A.this.method();
		}
	}
	
	void useB() {
		B b = new B();
		b.print();
	}
}
package ch09.sec05.exam02;

public class AExample {
	public static void main(String[] args) {
		A a = new A();
		
		a.useB();
	}
}
B-field
B-method
A-field
A-method