728x90

2025/04/22

 

자바의 최상위 클래스(Outer class)

  • 객체를 생성하지 않아도 접근 가능
  • 하지만, 내부에 인스턴스 필드/메서드를 사용하기 위해서는 객체 생성 필요
public class Outer {
    static int a = 10;
    static void write(int a) {
        System.out.println(a);
    }
    void read() {
        System.out.println(a);
    }
}

 

 

 

최상위 클래스에 static을 붙이지 않는 이유는??

💡 자바에서 모든 최상위 클래스는 원래 static처럼 동작하기 때문❗❗

static은 "외부 클래스에 종속되지 않겠다."는 의미인데
최상위 클래스는 원래 외부 클래스가 없으니 static을 붙일 필요도, 붙일 수도 없다.

class Outer {
    static class Inner {  // ✅ 가능
        ...
    }
}
----------------------------------------------
// ❌ 에러: Top-level에는 static class 선언 불가능
static class MyClass {
    ...
}

 

 

 

 


중첩 클래스 

🌔 클래스 내부에 선언한 클래스

🌔 클래스 멤버를 쉽게 사용할 수 있고, 외부에는 중첩 관계 클래스를 감춰 코드 복잡성 간소화 가능

중첩 클래스 종류

 

 

 

중첩 클래스의 class VS static class

class Outer {
    class Inner { }          // 비정적 중첩 클래스 == 인스턴스 멤버 클래스
    static class StaticInner { } // 정적 중첩 클래스
}
  • class Inner() : 외부 클래스의 인스턴스에 종속됨, 외부 인스턴스가 있어야 생성 가능
  • static class StaticInner() : 외부 인스턴스 없이도 사용 가능 ➡️ "독립적인 클래스"처럼 사용 가능
Outer.Inner inner = new Outer().new Inner();       // 외부 인스턴스 필요! new Outer()로 생성
Outer.StaticInner sin = new Outer.StaticInner();   // 외부 인스턴스 불필요!

 

 

 

 

static 필드/메서드는 그냥 쓰는데, static 클래스는 왜 new 해야 하지

📌 static 변수/메서드는 클래스에 소속되어 있어서
      → 메모리에 자동으로 올라가고, 클래스명으로 직접 접근 가능 
      → JVM이 알아서 메서드 영역에 올려줌

📌 static 클래스는 “틀”일 뿐
      → 
객체로 생성해서 사용 필수
      → static 클래스 내부에는 non-static 필드나 메서드도 있을 수 있음

 

그렇다면, static 클래스 안에 있는 필드나 메서드가 모두 static이라면 객체 생성 없이 사용 가능한가❓

💡객체 생성 없이 사용 가능❗마치 최상위 클래스처럼

class Outer {
    static class StaticUtil {
        static int add(int a, int b) {
            return a + b;
        }

        static String greeting = "Hello from static inner class!";
    }
}

public class Main {
    public static void main(String[] args) {
        // ✅ 객체 생성 없이 static 멤버 사용 가능
        int result = Outer.StaticUtil.add(3, 5);
        System.out.println(result); // 8

        System.out.println(Outer.StaticUtil.greeting); // Hello from static inner class!
    }
}​
728x90

+ Recent posts