티스토리 뷰

728x90

 

 

 

정적 멤버 클래스(정적 중첩 클래스)와 내부 클래스

즉, 내부 클래스가 static인지 여부에 따른 차이점을 알아보겠습니다.

 

 


 

 

Inner Class VS Nested Static Class

 

특징 비교

Inner Class

  • non-static nested class (스태틱이 아닌 중첩 클래스), non-static member class(비정적 멤버 클래스)라고도 한다.
  • 외부 클래스의 static 멤버/메서드non-static 멤버/메서드에 모두 직접 접근 가능하다.
  • 외부 클래스의 인스턴스를 생성해야만 인스턴스 생성이 가능하다. (외부참조: 메모리 누수 가능성)

Nested Static Class

  • static member class (정적 멤버 클래스)라고도 한다.
  • 외부 클래스의 static 멤버/메서드만 직접 접근이 가능하다.
  • 외부 클래스의 인스턴스를 생성할 필요가 없다. (독립적)
  • static이 붙어 있지만, 각각 생성한 두 객체는 다른 참조를 갖는다.

 

728x90

 

예제 코드

class OuterClass {

    // static
    private static String author = "DEVDOG";
    private static String sayHello() {
        return "Hello! This is ";
    }

    // non-static
    private String blogUrl = "https://the-dev.tistory.com";
    private String welcome() {
        return "Welcome to the blog: ";
    }

    /**
     * Non-static nested class (a.k.a. inner class)
     * Both static and non-static members of Outer class are accessible
     */
    class InnerClass {
        void print() {
            System.out.println("---InnerClass.print---");
            System.out.println(sayHello() + author);
            System.out.println(welcome() + blogUrl);
        }
    }
    /**
    * static nested class
    * Only static members of Outer class are directly accessible
    */ 
    static class NestedStaticClass {
        void print(){
            System.out.println("---NestedStaticClass.print---");
            System.out.println(sayHello() + author);
        }
    }
}

class Main {
    public static void main(String[] args) {

        // have to create Outer class instance then Inner class instance (external reference)
        OuterClass.InnerClass innerClass = new OuterClass().new InnerClass();
        innerClass.print();

        // Outer class instance not needed
        OuterClass.NestedStaticClass nestedStaticClass = new OuterClass.NestedStaticClass();
        nestedStaticClass.print();
    }
}

 

예제 코드 출력 화면

---InnerClass.print---
Hello! This is DEVDOG
Welcome to the blog: https://the-dev.tistory.com
---NestedStaticClass.print---
Hello! This is DEVDOG

 

 


 

 

reference:

https://geeksforgeeks.org/static-class-in-java/ 

 

Static class in Java - GeeksforGeeks

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

www.geeksforgeeks.org

 

728x90
Total
Today
Yesterday
«   2024/05   »
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
05-04 20:11