디폴트 메서드 (default method)

kmb·2022년 7월 8일
0

자바

목록 보기
24/31
post-thumbnail

Java8 부터 추가된 것 중 하나인 default method는 인터페이스 내부에서 구현된 메서드 앞에 default 라는 키워드가 추가 된것이다.

인터페이스는 본래 구현된 메서드가 있으면 안되지만 하위 호환성 때문에 메서드를 구현하게 된다.

모든 하위 클래스에서 동일한 새로운 메서드를 만들 상황이 발생 했을때 중복 구현 방지 및 기능을 쉽게 추가 할 수 있다.

public interface DefaultStaticInterface {

	static final String name ="test";
    static final int since = 2022;
    String getName();
    int getSince();
    
    default String getEmail() {
    	return name + "@naver.com";
    }
}

public class DefaultImplementedChild implements DefaultStaticInterface {

	@Override
    public String getName() {
    	return name;
    }
    
    @Override
    public int getSince() {
    	return since;
    }
}

abstract 클래스의 경우 extends를 사용하지만 dafault를 사용한 인터페이스는 implements 키워드를 사용해서 구현하면 된다.

또한 abstract 메서드의 경우 구현체에서 반드시 구현을 해야하지만, dafault 메서드는 구현하지 않아도된다.

이때 서브클래스에서 구현하지 않은 default 메서드에 접근시 슈퍼클래스의 default 메서드에 접근된다.

출처

  • 자바의 신 (책)
profile
꾸준하게

0개의 댓글