-
인터페이스 default 메소드와 static 메소드프로그래밍/Java 2022. 6. 9. 14:53
기본 메소드 (Default Methods)
- 인터페이스에 메소드 선언이 아니라 구현체를 제공하는 방법
- 해당 인터페이스를 구현한 클래스를 깨트리지 않고 새 기능을 추가할 수 있다.
- 기본 메소드는 구현체가 모르게 추가된 기능으로 그만큼 리스크가 있다.
- 컴파일 에러는 아니지만 구현체에 따라 런타임 에러가 발생할 수 있다.
- 반드시 문서화 할 것. (@implSpec 자바독 태그 사용)
public interface Foo { void printName(); /* * @implSpec * 이 구현체는 getName()으로 가져온 문자열을 대문자로 바꿔 출력한다. */ // getName() 에 null 값이 들어올 수 있음. 문제가 된다면 구현 클래스에서 재정의하자. default void printNameUpperCase() { System.out.println(getName().toUpperCase()); } String getName(); }
- Object가 제공하는 기능 (equals, hasCode)는 기본 메소드로 제공할 수 없다.
- 구현체가 재정의해야 한다.
- 본인이 수정할 수 있는 인터페이스에만 기본 메소드를 제공할 수 있다.
- 인터페이스를 상속받는 인터페이스에서 다시 추상 메소드로 변경할 수 있다.
- 인터페이스 구현체가 재정의 할 수도 있다.
- 인터페이스 다중 상속 시 두 곳 모두 default 메소드가 존재할 경우엔 구현 클래스에서 재정의 해야한다.
public interface Bar { default void printNameUpperCase() { System.out.println("Bar"); } }
public interface Foo { default void printNameUpperCase() { System.out.println(getName().toUpperCase()); } }
public class DefaultFoo implements Foo, Bar{ String name; public DefaultFoo(String name) { this.name = name; } @Override public void printNameUpperCase() { System.out.println("재정의된 메소드"); } @Override public String getName() { return this.name; } }
Static Methods
- 해당 타입 관련 헬터 또는 유틸리티 메소드를 제공할 때 인터페이스에 스태틱 메소드를 제공할 수 있다.
public interface Foo { static void staticMethodTest() { System.out.println("it's staticMethodTest"); } } // Foo.staticMethodTest();
참고
백기선 - 더 자바, Java8
https://www.inflearn.com/course/the-java-java8/dashboard'프로그래밍 > Java' 카테고리의 다른 글
Java Virtual Thread (1) (1) 2024.06.16 CompletableFuture (3) - Callable 과 Future (0) 2022.06.14 메소드 레퍼런스 (0) 2022.06.08 자바에서 제공하는 함수형 인터페이스 (0) 2022.06.07 함수형 인터페이스와 람다 표현식 소개 (0) 2022.06.07