java
Nested class의 개념
easy16
2019. 9. 15. 21:00
static 유무의 차이
1, static nested 클래스
-> 논리적으로 묶기 위해, class의 내부에 존재하며 outer 클래스의 접근은 여타 클래스와 동일
-> 차이점으로 static 멤버의 경우 Outer -> Inner , Inner -> Outer 모두 private static 멤버는 접근가능함.
: nested 클래스 안에 nested class 생성 불가
ex)아래와 같이 사용 불가
public class Test{ class A{ class B{ } static class C{ //The member type C cannot be declared static; static types can only be declared in static or top level types } } }
2, inner 클래스
a, local inner class (내부 클래스)
b, anonymous inner class(익명 클래스)
-> Outer 클래스의 private 한 요소들을 참조 가능하다.
public class A { private int A = 10; private static final int staticA = 10; private void foo() { System.out.println("A"); } class B { public void printPrivateMember() { System.out.println( A);//print private A's method foo();//call A's private method } } static class C { private static final int staticC = 30; public void print() { System.out.println("C : "+ staticA);//외부의 private한 static 멤버 까지 참조 가능. } } public void print() { System.out.println("A : "+ C.staticC);//반대로 내부의 private한 static 멤버 까지 참조 가능. } }
출처 : 자바의 신