JAVA/포스팅

자바 인터페이스의 작성

짜집퍼박사(짜박) 2023. 11. 13. 00:18

자바에서 인터페이스를 작성하는 방법은 다음과 같습니다. 인터페이스는 일종의 계약(Contract)으로, 특정 메서드의 구현을 강제하고, 클래스가 해당 인터페이스를 구현하면 해당 메서드를 반드시 제공해야 합니다.

 

1. 인터페이스 선언

interface 키워드를 사용하여 인터페이스를 선언합니다.
메서드는 기본적으로 추상 메서드로 선언됩니다.

interface MyInterface {
    // 추상 메서드
    void myMethod();

    // 디폴트 메서드
    default void defaultMethod() {
        System.out.println("Default implementation");
    }

    // 정적 메서드
    static void staticMethod() {
        System.out.println("Static method");
    }
}

 

2. 인터페이스 구현

클래스에서 implements 키워드를 사용하여 인터페이스를 구현합니다.
모든 추상 메서드를 반드시 오버라이드해야 합니다.

class MyClass implements MyInterface {
    // 추상 메서드의 구현
    public void myMethod() {
        System.out.println("MyMethod implementation");
    }
}

 

3. 인터페이스 사용

인터페이스를 구현한 클래스의 인스턴스를 생성하여 사용합니다.

public class Main {
    public static void main(String[] args) {
        MyInterface obj = new MyClass();
        obj.myMethod();          // MyMethod implementation
        obj.defaultMethod();     // Default implementation
        MyInterface.staticMethod();  // Static method
    }
}

 

4. 다중 인터페이스 구현

하나의 클래스가 여러 개의 인터페이스를 구현할 수 있습니다.

interface InterfaceA {
    void methodA();
}

interface InterfaceB {
    void methodB();
}

class MyImplementation implements InterfaceA, InterfaceB {
    public void methodA() {
        System.out.println("Implementation of methodA");
    }

    public void methodB() {
        System.out.println("Implementation of methodB");
    }
}

이렇게 작성된 인터페이스는 클래스들이 특정 메서드들을 반드시 제공하도록 강제합니다. 인터페이스는 자바에서 다중 상속을 지원하기 위한 강력한 도구 중 하나이며, 코드의 재사용성과 유지보수성을 높일 수 있도록 도와줍니다.

 

With ChatGPT

'JAVA > 포스팅' 카테고리의 다른 글

자바 인터페이스의 구현  (0) 2023.11.13
자바 인터페이스의 상속  (0) 2023.11.13
자바 인터페이스  (0) 2023.11.13
자바 추상클래스의 작성  (0) 2023.11.12
자바 추상클래스  (0) 2023.11.12