Java의 인터페이스

Java로 배우는 객체 지향 프로그래밍 입문

Sani Yusuf

Lead Software Engineering Content Developer

상속의 한계

  • 상속에서는 모든 멤버가 함께 상속됨
  • 특정 멤버만 선택적으로 상속할 수 없음

  // Car 클래스   
  class Car {
    // 배터리 용량은 전기차에만 해당
    public int batteryCapacity;
    void drive() {

    }  

  }


  // Toyota 클래스
  class Toyota extends Car {  
    void drive(){

    }           
  }


// Main 클래스 public static class Main { public static void main(String[] args) { Toyota myToyota = new Toyota(); // 전기차가 아니어도 모든 차가 // "batteryCapacity"를 상속받음 System.out.println( myToyota.batteryCapacity); // 해당 없음 } }
Java로 배우는 객체 지향 프로그래밍 입문

인터페이스 만들기

  • 인터페이스는 속성과 메서드를 선택적으로 제공함
  • 클래스는 implements 키워드로 인터페이스를 사용함

  // ElectricCar 인터페이스 
  interface ElectricCar {

  }





  // ElectricCar 인터페이스를
  // 구현하는 Tesla
  class Tesla implements ElectricCar {

  }








Java로 배우는 객체 지향 프로그래밍 입문

인터페이스에 속성 추가

  • 속성은 관례적으로 UPPER_SNAKE_CASE 사용
  • 값은 즉시 할당되며 변경할 수 없음
  • 속성은 내부적으로 public static final

  interface ElectricCar {
    // 묵시적으로 public static final
    // 변경 불가
    int BATTERY_CAPACITY = 310;

  }




Java로 배우는 객체 지향 프로그래밍 입문

인터페이스에 메서드 추가

  • 인터페이스는 보통 메서드를 담음
  • 메서드는 기본적으로 구현 없는 abstract
  • 구현이 있는 구체 메서드도 가능
  • 모든 abstract 메서드는 하위 클래스에서 구현해야 함
  interface ElectricCar {
    // 묵시적으로 public static final
    // 변경 불가
    int BATTERY_CAPACITY = 310;


// 기본적으로 추상 메서드 void charge();
// 구체 메서드 void autoPark() { }
}
class Tesla implements ElectricCar { // 반드시 구현 public void charge() { } }
Java로 배우는 객체 지향 프로그래밍 입문

연습해 봅시다!

Java로 배우는 객체 지향 프로그래밍 입문

Preparing Video For Download...