IT 도서/이펙티브 자바

[클래스와 인터페이스] 추상 클래스보다는 인터페이스를 우선하라

호_두씨 2023. 8. 1. 08:38

들어가기 전에

추상 클래스를 썼을 때 

타입을 추상클래스로 정의해두면 그 타입에 기능을 추가하는 방법은 상속뿐이다.

자바는 단일 상속만 지원하므로 추상 클래스는 새로운 타입을 정의하는데 제약이 있다.

 

인터페이스의 장점

장점1 : 계층구조가 없는 타입 프레임워크를 만들 수 있다.

-다중 구현가능

-계층을 엄격히 구분하기 어려운 개념 표현 가능

-확장하여 제 3의 인터페이스를 정의할 수 있다.

public interface Singer{
	AudioClip sing(Song s);
}

public interface Songwriter{
	Song Compose(int chartPosition);
}
public interface SringerSongwriter extends Singer, Songwriter{
	AudioClip strum();
	void actSensitive;
}

장점2 : 디폴트 메서드 활용

디폴트 메서드란?
자바 8에서 등장한 개념으로 메소드 선언 시에 default를 명시하게 되면 인터페이스 내부에서도 로직이 포함된 메소드를 선언할 수 있습니다.

-인터페이스 중 구현 방법이 명백한 것이 있다면 그 구현을 디폴트 메서드로 제공해준다.
-상속하려는 사람을 위한 설명을 @impleSec 자바독 태그를 붙여 문서화해야한다.

 

예시)

자바 8의 Collection 인터페이스에 추가된 디폴트 메서드

public interface Collection<E> extends Iterable<E> {

/**
 * Removes all of the elements of this collection that satisfy the given
 * predicate.  Errors or runtime exceptions thrown during iteration or by
 * the predicate are relayed to the caller.
 *
 * @implSpec
 * The default implementation traverses all elements of the collection using
 * its {@link #iterator}.  Each matching element is removed using
 * {@link Iterator#remove()}.  If the collection's iterator does not
 * support removal then an {@code UnsupportedOperationException} will be
 * thrown on the first matching element.
 *
 * @param filter a predicate which returns {@code true} for elements to be
 *        removed
 * @return {@code true} if any elements were removed
 * @throws NullPointerException if the specified filter is null
 * @throws UnsupportedOperationException if elements cannot be removed
 *         from this collection.  Implementations may throw this exception if a
 *         matching element cannot be removed or if, in general, removal is not
 *         supported.
 * @since 1.8
 */
		 default boolean removeIf(Predicate<? super E> filter) {
		        Objects.requireNonNull(filter);
		        boolean removed = false;
		        final Iterator<E> each = iterator();
		        while (each.hasNext()) {
		            if (filter.test(each.next())) {
		                each.remove();
		                removed = true;
		            }
		        }
		        return removed;
		    }
}

 

Reference  및 참고

이펙티브 자바 Effective Java 3/E (조슈아블로크)