2 minute read

목표

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

학습할 것 (필수)

인터페이스 정의하는 방법

인터페이스: 추상 메소드와 상수만으로 구성된 추상 클래스

// public static final 생략 가능, 생략 시 컴파일 시 자동 추가
// public abstract 생략 가능, 생략 시 컴파일 시 자동 추가
public interface 인터페이스명 [extends 인터페이스명, ...]{
	(public static final) 상수 선언; 
	(public abstract) 추상 메소드 선언;
}
public interface Map<K,V> {
	...
	int size();
    boolean isEmpty();
    boolean containsKey(Object key);
	...
}

인터페이스 구현하는 방법

implements 키워드를 사용해 인터페이스를 구현하는 클래스를 만든다.

인터페이스

public interface Map<K,V> {
	...
    int size();
    V get(Object key);
	...
}

인터페이스를 구현하는 클래스

public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable {
	...
	public int size() {
        return size;
    }
	...
	public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }
	...
}

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

  • 인터페이스 타입의 참조변수
    인터페이스도 인터페이스 타입의 참조변수로 이를 구현한 클래스의 인스턴스를 참조할 수 있고, 인터페이스의 타입으로 형변환도 가능하다.
interface Interface{
    void doSomething();
}
class Class implements Interface{
    @Override
    public void doSomething() {
        System.out.println("Class.doSomething()");
    }
}
public class Test {
    public static void main(String[] args) {
        Interface i = new Class();
        Interface i2 = (Interface) new Class();

        i.doSomething();
        i2.doSomething();
    }
}
  • 인터페이스 타입의 매개변수
public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable {
    ...
    public void putAll(Map<? extends K, ? extends V> m) {
        putMapEntries(m, true);
    }
    ...
}
  • 인터페이스 리턴타입
...
class Class implements Interface{
    ...
    Interface returnInterface(){
        Interface c = new Class();
        return c;
    }
}
public class Test {
    public static void main(String[] args) {
        Class c = new Class();
        System.out.println(c.returnInterface());
    }
}

인터페이스 상속

인터페이스도 클래스처럼 상속을 할 수 있으며, 다중 구현이 가능하다.
인터페이스가 여러개 올 수 있다. = 여러가지 타입으로 변수를 선언할 수 있다.

// 인터페이스는 다중 상속이 가능하다(extends 인터페이스, 인터페이스, ...)
public interface 인터페이스명 extends 인터페이스명, ...{
	(public static final) 상수 선언; 
	(public abstract) 추상 메소드 선언;
}
public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable {
        // Map, Cloneable, Serializable 모두 인터페이스
}

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

자바 8부터 인터페이스도 기본 메소드(Default Method) 사용이 가능해졌다. 인터페이스를 구현한 구현체(클래스)에서 인터페이스의 추상 메소드를 모두 overriding 해서 사용해야 하지만, 기본 메소드는 구현할 필요가 없다.

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

자바 8부터 추가할 수 있게 되었으며, static 메소드는 인스턴스와 관계가 없는 독립적인 메소드이므로 인터페이스에 추가 못할 이유가 없고, 개발의 유연성을 위해 제약이 풀렸다.

optional

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


참고 서적

뇌를 자극하는 Java 프로그래밍
알기 쉽게 해설한 Java
열혈강의 객체 중심 Java
이펙티브 자바


live-study with whiteship