gpt-4-turbo-2024-04-09· OpenAI
WildChat-4.8M (AI2)
Java에서 class 앞에 static 키워드가 붙을 수 있는 경우는 Nested class일 때에만 가능한거지?
- User
Java에서 class 앞에 static 키워드가 붙을 수 있는 경우는 Nested class일 때에만 가능한거지?
- Assistant
네, 맞습니다. Java에서
static키워드를 class 선언 앞에 사용할 수 있는 경우는 nested class, 즉 내부 클래스일 때 뿐입니다. static nested class는 외부 클래스 인스턴스와 독립적으로 존재할 수 있는 내부 클래스를 의미합니다. 이 static nested class는 외부 클래스의 private 멤버를 포함한 모든 static 멤버에 접근할 수 있습니다.기본적으로 내부 클래스(inner class)는 외부 클래스의 인스턴스에 속해 있으며, 이를 통해 외부 클래스의 인스턴스 변수 및 메소드에 직접 접근할 수 있습니다. 하지만 static nested class는 그러한 접근 권한이 제한되어 있으며, 외부 클래스의 static 멤버에만 접근할 수 있습니다. 이러한 특성 때문에 static nested class는 외부 클래스의 인스턴스 없이도 생성될 수 있습니다.
예를 들어 다음과 같이 정의할 수 있습니다:
javapublic class OuterClass { private static int outerStaticNum = 10; static class NestedStaticClass { public void printMessage() { // 외부 클래스의 static 변수에 접근 가능 System.out.println("Outer static num is: " + outerStaticNum); } } }이 경우에는
OuterClass.NestedStaticClass인스턴스를 생성해 메소드를 호출할 수 있습니다:javaOuterClass.NestedStaticClass nested = new OuterClass.NestedStaticClass(); nested.printMessage();