static inner class는 static영역에 처음부터 상주하게 된다. 즉 프로세스가 실행되는 시점부터

이미 메모리에 올라가게된다. 그러므로 static inner class는 outer class의 static변수에는 접근이 가능하다.

 

사실 static inner class는 inner class 라 보기에 어려운 점이 한두가지가 아닌것이 일단 outer class에 대한

reference정보가 없다. 당연한것이 outer class는 static class가 아니고 인스턴스가 생성되기 전이므로

정보가 없게된다. 그러므로 Memory Leak을 관리하기 위한 이점이 있는편이다.

 

다만 static inner class라고 하더라도 outer class의 참조값 혹은 context를 받아와야하는 경우가 생긴다.

그럴때는, WeakRefernce를 사용해서 받아줘야한다.

 

 

 

 

-궁금해서 실험해본내역

static inner class 라고해서 내부의 변수들이 모두 static 변수는 아니다.

명시적으로 static inner class에 static으로 선언한애들만 static 변수가 되는것이다.

static inner class 의 일반변수들도 new로 인하여 인스턴스가 생성될때 할당되며 그때의 인스턴스를통해

맴버변수들에 접근할 수 있게된다. 

 

그러므로 static inner class라고 하더라도 멤버변수들이 outer class의 context같은 참조값을 들고있게된다면

위험한건 마찬가지다. 그러므로 WeakReference 변수로 받아줘야할 필요가 있다.

 

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
31
32
 
public class Main {
    static int c = 20;
    
    
    public static void main(String[] args) {
        
        TestClass tc1 = new TestClass();
        tc1.a = 3;
        
        TestClass tc2 = new TestClass();
        tc2.a = 4;
        
        System.out.println("tc1.a="+tc1.a+"  tc2.a="+tc2.a);
        System.out.println("tc1="+tc1+"  tc2="+tc2);
        
        System.out.println("tc1.b="+tc1.b+"  tc2.b="+tc2.b);
        
        // Main.TestClass.a = 3; //컴파일에러
        System.out.println("static TestClass.c=" + TestClass.c);
 
    }
    
    static class TestClass {
        int a;
        int b = c;
        static int c = 200;
        
    }
    
}
 
 
 

 

 

 

참고

 

https://movefast.tistory.com/41

 

14. Inner Class (Nested Class) and Interface - 중첩 클래스와 중첩 인터페이스

▶ 중첩 클래스 및 중첩 인터페이스를 사용하는 이유 - 자바는 객체 지향 프로그램으로 각 클래스가 관계를 맺으며 상호작용을 한다. 어떤 클래스는 많은 클래스와 상호작용을 하기도 하지만, 다른 어떤 클래스는..

movefast.tistory.com

일반 inner class는 outer class의 인스턴스를 먼저 생성하고나서야 inner class의 인스턴스를 생성할 수 있다.

 

static inner class는, outer class의 이름으로바로 접근하여 인스턴스를 생성할수있다.

 

이점만 봐도 사실 outer와 static inner class간의 메모리 영역은 다른곳에 상주하고있다고 생각을해도 될것같다.

 

 

 

 

+ Recent posts