English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Java에서인터페이스클래스와 유사하지만, final과 static의 추상 메서드와 필드만 포함된 것입니다.
甲static 메서드에서는静态 키워드를 사용하여 선언된 static 메서드가 메모리에 로드됩니다. 인스턴스화 없이 클래스 이름을 사용하여静态 메서드에 접근할 수 있습니다.
Java8최초에, 인터페이스(본문을 포함한)에서静态 메서드를 사용할 수 있습니다. 그들에 대해 클래스 이름을 사용하여 호출해야 합니다. 그들도 클래스의静态 메서드와 마찬가지로 호출됩니다.
다음 예제에서, 우리는 인터페이스에서静态 메서드를 정의하고 그 인터페이스를 구현하는 클래스에서 그것을 접근합니다.
interface MyInterface{ public void demo(); public static void display() { System.out.println("This is a static method"); } } public class InterfaceExample{ public void demo() { System.out.println("This is the implementation of the demo method"); } public static void main(String args[]) { InterfaceExample obj = new InterfaceExample(); obj.demo(); MyInterface.display(); } }
출력 결과
This is the implementation of the demo method This is a static method
甲정적 블록는 코드가 정적 키워드를 사용하는 블록입니다. 일반적으로 이들은 정적 멤버를 초기화하는 데 사용됩니다. JVM은 클래스를 로드할 때 메인 메서드 앞에 정적 블록을 실행합니다.
public class MyClass { static{ System.out.println("Hello this is a static block"); } public static void main(String args[]){ System.out.println("This is main method"); } }
출력 결과
Hello this is a static block This is main method
주로, 선언할 때 이미 초기화되지 않은 정적 블록이 있으면, 그들은 클래스를 초기화하는 데 사용됩니다/정적 변수.
인터페이스에서 필드를 선언할 때, 그에 대한 값을 할당해야 합니다. 그렇지 않으면 컴파일 시 오류가 발생합니다.
interface Test{ public abstract void demo(); public static final int num; }
Test.java:3: error: = expected public static final int num; ^ 1 error
당신이 인터페이스에서 정적 최종 변수에 값을 할당할 때, 이 문제를 해결합니다.
interface Test{ public abstract void demo(); public static final int num = 400; }
따라서, 인터페이스에 정적 블록을 포함하지 않아도 됩니다.