HOWTO · Java
Java의 정적 인터페이스
이 튜토리얼에서는 Java의 정적 인터페이스에 대해 설명합니다.
인터페이스는 Java와 같은 객체 지향 프로그래밍 언어에서 가장 일반적으로 사용되는 요소이며 정적이라는 키워드는 요소를 고정하는 데 사용됩니다.
이 기사에서는 정적 인터페이스를 선언하는 방법을 보여줍니다. 또한 주제를 더 쉽게 만들기 위해 필요한 예와 설명을 사용하여 주제를 논의합니다.
인터페이스가 중첩되거나 다른 인터페이스의 하위인 경우 인터페이스를 정적으로 선언할 수 있습니다.
Java의 중첩 인터페이스에서 정적 사용
아래 예제에서는 중첩된 인터페이스에서 정적을 사용하는 방법을 보여줍니다. 그러나 중첩된 인터페이스를 선언할 때 정적 키워드를 사용하는 것은 선택 사항입니다. 정적 키워드를 사용하지 않을 때 동일한 결과가 표시되기 때문입니다.
이제 우리 예제의 코드는 아래와 같습니다.
import File.MyInterface.NastedInterface;
interface MyInterface { // Declaring an interface
public static interface NastedInterface { // Declaring a nasted interface
// Declaring static method
static void PrintMSG() {
System.out.println("This is a message from a nested interface!!!");
}
}
}
// Creating a class that implements the nested interface
public class StaticInterface implements MyInterface.NastedInterface {
public static void main(String[] args) {
// Calling the static method from the interface
NastedInterface.PrintMSG();
}
}
각 행의 목적은 주석으로 남습니다. 중첩된 인터페이스에 대한 정적 키워드는 선택 사항입니다.
위의 예제를 실행하면 콘솔에 아래와 같은 출력이 표시됩니다.
This is a message from a nested interface!!!
Java의 인터페이스 내부에서 정적 메서드 사용
또한 인터페이스 내에서 정적 요소 각각을 선언하여 정적 인터페이스를 생성할 수 있습니다. 메소드를 정적으로 선언할 때 인터페이스 내부에 메소드를 정의해야 합니다.
아래 예제를 살펴보겠습니다.
// Declaring an interface
interface MyInterface {
// A static method
static void PrintMSG() {
System.out.println("This is a message from the interface!!!"); // Method is defined
}
// An abstract method
void OverrideMethod(String str);
}
// Implementation Class
public class StaticInterface implements MyInterface {
public static void main(String[] args) {
StaticInterface DemoInterface = new StaticInterface(); // Creating an interface object
// An static method from the interface is called
MyInterface.PrintMSG();
// An abstract method from interface is called
DemoInterface.OverrideMethod("This is a message from class!!!");
}
// Overriding the abstract method
@Override
public void OverrideMethod(String str) {
System.out.println(str); // Defining the abstract method
}
}
위의 예에서 인터페이스 내에서 정적의 사용을 설명했습니다.
각 행의 목적은 주석으로 남습니다. 위 예제의 인터페이스에서 PrintMSG라는 정적 메서드와 OverrideMethod라는 추상 메서드에서 두 가지 메서드를 선언했습니다.
PrintMSG 메서드는 인터페이스 내부의 정적 메서드이므로 인터페이스에 정의되어 있음을 알 수 있습니다.
위의 예제를 실행하면 콘솔에 아래와 같은 출력이 표시됩니다.
This is a message from the interface!!!
This is a message from class!!!