Skip to content

Latest commit

 

History

History
184 lines (138 loc) · 5.63 KB

8.Interface.md

File metadata and controls

184 lines (138 loc) · 5.63 KB

Goal

자바의 인터페이스에 대해 학습하세요.

목차

  • 인터페이스 정의하는 방법
  • 인터페이스 구현하는 방법
  • 인터페이스 레퍼런스를 통해 구현체를 사용하는 방법
  • 인터페이스 상속
  • 인터페이스의 기본 메소드 (Default Method), 자바 8
  • 인터페이스의 static 메소드, 자바 8
  • 인터페이스의 private 메소드, 자바 9

인터페이스 정의하는 방법

자바에서 인터페이스는 참조 타입이다. 클래스 정의와 비슷하지만 class 대신 interface를 사용한다.

public interface OperateCar {

   // constant declarations, if any

   // method signatures

   // An enum with values RIGHT, LEFT
   int turn(Direction direction,
            double radius,
            double startSpeed,
            double endSpeed);
            // method signature는 {} 없이 ; 으로 끝난다.
   int changeLanes(Direction direction,
                   double startSpeed,
                   double endSpeed);
   int signalTurn(Direction direction,
                  boolean signalOn);
   int getRadarFront(double distanceToCar,
                     double speedOfCar);
   int getRadarRear(double distanceToCar,
                    double speedOfCar);
         ......
   // more method signatures
}

인터페이스 구현하는 방법

// 인터페이스를 구현하는 클래스에서 해당 메소드를 오버라이드 한다.
public class OperateBMW760i implements OperateCar {

    // the OperateCar method signatures, with implementation --
    int signalTurn(Direction direction, boolean signalOn) {
        // 추상 메서드의 실제 구현
    }
    // ...
}

인터페이스 레퍼런스를 통해 구현체를 사용하는 방법

인터페이스를 구현한 클래스의 종류에 상관없이 인터페이스 타입으로 사용 가능함

// ojbect1, object2 는 Relatable 인터페이스를 구현한 어떤 클래스의 인스턴스라도 가능하다.
public Object findLargest(Object object1, Object object2) {
   Relatable obj1 = (Relatable)object1;
   Relatable obj2 = (Relatable)object2;
   if ((obj1).isLargerThan(obj2) > 0)
      return object1;
   else
      return object2;
}

인터페이스 상속

인터페이스도 클래스 처럼 상속할수 있다.

클래스는 하나만 상속 할수 있으나 인터페이스는 여러개 상속할수 있다.


// 상속 없이 메소드 추가하는 예
public interface DoIt {
   void doSomething(int i, double x);
   int doSomethingElse(String s);
}

public interface DoIt {

   void doSomething(int i, double x);
   int doSomethingElse(String s);
   boolean didItWork(int i, double x, String s);
}


// 인터페이스에 상속 적용한 예 DoItPlus 가 DoIt 을 상속받아 새로운 인터페이스를 만든다.
public interface DoItPlus extends DoIt {

   boolean didItWork(int i, double x, String s);

}

인터페이스의 기본 메소드 (Default Method), 자바 8

인터페이스가 default 로 선언되면 메소드를 구현할수 있다.

    public interface Calculator {
        public int plus(int i, int j);
        public int multiple(int i, int j);
        default int exec(int i, int j){
            // default로 선언 인터페이스에서 메소드를 구현함
            // default 없을때는 모든 클래스들 메서드 추가 구현해야...
            // 원한다면 인터페이스를 구현한 클래스에서 오버라이드 할수 있음
            return i + j;
        }
    }

    //Calculator인터페이스를 구현한 MyCalculator클래스
    public class MyCalculator implements Calculator {

        @Override
        public int plus(int i, int j) {
            return i + j;
        }

        @Override
        public int multiple(int i, int j) {
            return i * j;
        }
    }

    public class MyCalculatorExam {
        public static void main(String[] args){
            Calculator cal = new MyCalculator();
            int value = cal.exec(5, 10);    // 인터페이스의 default 메소드 이용함
            System.out.println(value);
        }
    }

인터페이스의 static 메소드, 자바 8

인터페이스가 static 메소드는 인터페이스 구현한 클래스에서 오버라이드 할 수 없음. 주로 유틸리티성 클래스 에서 사용함

public interface TimeClient {
    // ...
    static public ZoneId getZoneId (String zoneString) {
        try {
            return ZoneId.of(zoneString);
        } catch (DateTimeException e) {
            System.err.println("Invalid time zone: " + zoneString +
                "; using default time zone instead.");
            return ZoneId.systemDefault();
        }
    }

    default public ZonedDateTime getZonedDateTime(String zoneString) {
        return ZonedDateTime.of(getLocalDateTime(), getZoneId(zoneString));
    }
}

인터페이스의 private 메소드, 자바 9

오라클 문서 검색 해도 못찻겠네요.. 추후 더 공부할 사항입니다.