클래스들이 필수로 구현해야하는 추상 자료형으로 객체의 사용방법을 제시해준다.
인터페이스는 추상메서드와 상수로만 이루어져있고 구현된 코드가 없기에 인스턴스도 사용 불가능하다.
public interface TV{ public void turnOn(); public void turnOff(); }
public class LedTV implements TV{ public void on(){ System.out.println("켜다"); } public void off(){ System.out.println("끄다"); } }
LedTV 클래스를 생성하고 TV 인터페이스를 implements 키워드로 구현하여 인터페이스의 추상메서드를 모두 재정의한다.
Java 8이 등장함에 따라 인터페이스 정의가 변경됨.
그중 하나가 default 메소드로 default 키워드로 선언된 경우에 메소드가 구현될 수 있으며
클래스는 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로 선언함으로 메소드를 구현할 수 있다. 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); System.out.println(value); } }
static 메소드를 사용하여 간단한 기능을 가지는 유틸리티성 인터페이스를 만들 수 있다.
public interface Calculator { public int plus(int i, int j); public int multiple(int i, int j); default int exec(int i, int j){ return i + j; } public static int exec2(int i, int j){ //static 메소드 return i * j; } } //인터페이스에서 정의한 static메소드는 반드시 인터페이스명.메소드 형식으로 호출해야한다. public class MyCalculatorExam { public static void main(String[] args){ Calculator cal = new MyCalculator(); int value = cal.exec(5, 10); System.out.println(value); int value2 = Calculator.exec2(5, 10); //static메소드 호출 System.out.println(value2); } }