1 분 소요

인터페이스(Interfaces)

  • 인터페이스는 온전히 추상으로만 이루어진 클래스입니다.
    // 인터페이스
    interface Animal {
    public void animalSound(); // 인터페이스 메서드
    public void run(); // 인터페이스 메서드
    }
    
  • 인터페이스 메서드를 사용하기 위해서는 다른 클래스에서 implements를 메서드 정의를 할 수 있습니다.
  • 인터페이스는 extends가 아니라 implements를 사용합니다.
    // 인터페이스
    interface Animal {
    public void animalSound();
    public void sleep();
    }
    
    // Pig 가 Animal 인터페이스를 상속받음
    class Ping implements Animal {
    public void animalSound() {
      // animalSound() 메서드 정의는 여기서
      System.out.println("꾸익꾸익");
    }
    public void sleep() {
      // sleep() 메서드 정의는 여기서
      System.out.println("Zzz");
    }
    }
    
    class Main {
    public static void main(String[] args) {
      Pig myPig = new Pig();
      myPig.animalSound();
      myPig.sleep();
    }
    }
    
  • 인터페이스 주의점
    • 추상 클래스와 마찬가지로 인터페이스는 객체 생성을 하지 못함.
    • 인터페이스 메서드는 정의가 되어있으면 안됨. 자식 클래스에서 정의.
    • 인터페이스를 상속 받았다면 인터페이스의 모든 메서드를 오버라이드 해야함.
    • 인터페이스의 메서드는 기본적으로 abstractpublic 입니다.
    • 인터페이스의 속성은 기본적으로 public, static, final 입니다.
    • 인터페이스는 생성자가 없습니다(객체 생성을 못함으로).

다중 인터페이스(Multiple Interfaces)

  • 여러 개의 인터페이스를 상속 받을 때는 콤마( , )를 통해 나눌 수 있습니다.
    interface FirstInterface {
    public void myMethod();
    }
    
    interface SecondInterface {
    public void myOtherMethod();
    }
    
    class DemoClass implements FirstInterface, SecondInterface {
    public void myMethod() {
      System.out.println("아무 문자");
    }
    public void myOtherMethod() {
      System.out.println("다른 문자");
    }
    }
    
    class Main {
    public static void main(String[] args) {
      DemoClass obj = new DemoClass();
      obj.myMethod();
      obj.myOtherMethod();
    }
    }