2013-08-30 2 views
0

다음은 실행하려고 시도한 코드입니다. 출력은 Good입니다. 그래서 우리는 클래스에 의해 구현 된 인터페이스 변수를 사용할 수 있습니까?왜 대답이 "좋아"될까요?

interface IDummyInterface { 
    public String TYPE = "Good"; 
} 

class Test implements IDummyInterface { 

} 

public class MyApplication { 
    public static void main(String[] args) { 
     System.out.println(Test.TYPE); 
    } 
} 

답변

6

인터페이스를 구현하는 모든 클래스와 해당 인터페이스를 구현하는 클래스를 확장하는 모든 클래스는 해당 인터페이스 변수를 모두 상속받습니다. 인터페이스에서 변수를 선언하는 방법에 관계없이 모든 인터페이스 변수는 public static final입니다. 따라서 클래스의 인스턴스가 아닌 클래스 이름 만 사용하여 액세스 할 수 있습니다.

+1

감사합니다. 건배 –

+0

그렇기 때문에 인터페이스 선언에서'public'을 생략 할 수 있습니다. – vertti

2

Test 구현은 IDummyInterfaceIDummyInterface .so는 모든 변수는 변수 실제로 static final이다

2

상속된다. 그리고 static이기 때문에 클래스에서 상속받은 다른 모든 클래스를 통해 액세스 할 수있는 클래스에서 선언 된 모든 정적 변수와 동일한 규칙을 따릅니다. 이와 관련하여 인터페이스는 클래스처럼 작동합니다.

class StaticTestParent { public static final int VALUE = 1; } 
class StaticTestChild extends StaticTestParent { } 

static { 
    System.out.println(StaticTestChild.VALUE); 
} 
관련 문제