Skip to content

Latest commit

 

History

History
79 lines (70 loc) · 2.56 KB

File metadata and controls

79 lines (70 loc) · 2.56 KB

Interface

  • Interface에서 선언한 변수는 컴파일 과정에서 상수(public static final)화 된다.
  ex) double pi = 3.14; -> public static final double pi;
  • Interface에서 선언한 함수(메소드)는 컴파일 과정에서 추상 메소드(abstract)로 변환된다.
  • Interface는 여러개를 상속받을 수 있다.
public class Main implements firstInt, secondInt, .... { ~~~~ }
  • Interface는 상수 필드, 추상 메소드, default 메소드, static 메소드의 구조를 가질 수 있다.
    (default와 static 메소드의 경우 java 8 이상부터 사용 가능)
public interface Calc {
  // Constant Field
  double pi = 3.14;
  
  // Abstract Method
  public abstract int add(int a, int b);
  // 이 때 public abstract는 생략이 가능하다.
  
  // Default Method
  default double multiple(double a, double b) {
    return a * b;
  }
  
  // Static Method
  public static double divide(double a, double b) {
    return a / b;
  }
}
  • Interface를 구현한 클래스는 Interface Type으로 변수를 선언하여 인스턴스를 생성할 수 있다.
    (인터페이스는 구현 코드가 없기 때문에 타입 상속이라고도 한다.)
class CalcTest implements Calc {
  public int add(int a, int b)  {
    return a + b;
  }
}

class Main extends CalcTest {
  public static void main(String[] args)  {
    CalcTest calcTest = new CalcTest();
    Calc calc = new CalcTest();   // Upcasting과 같은 원리
  }
}
  • Interface가 Interface를 상속받을 수 있다.
public interface firstInt {
  default void sources()  {
    System.out.println("First Interface's Method);
  }
}

public interface secondInt extends firstInt{
  default void sources()  {
    System.out.println("Second Interface's Method);
  }
}

public class InterTest implements firstInt, secondInt  {
  public static void main(String[] args)  {
    new InterTest().sources();
    // Second Interface's Method가 출력된다.
  }
}
  • 위의 경우 firstInt를 상속받은 secondInt가 상속의 우선권을 갖는다.

Default Method

  • 인터페이스가 변경이 되는 경우, 이를 구현하고 있는 모든 클래스에서 변경되는 부분을 구현해야 하는 문제가 발생한다.(하위 호환성)
  • 이를 해결하기 위해 인터페이스에 메소드를 구현하게 해주는 것이 Default Method이다.

Static Method

  • Static영역에 생성되어 객체가 생성되기 전(객체가 생성되는 경우 Heap Memory에 할당이 된다.)에 접근이 가능하다.
    (추후에 Java Data Area에 대한 포스팅 예정)