Notice
Recent Posts
Recent Comments
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
관리 메뉴

충분히 쌓여가는

8.5 디폴트 메소드 본문

이것이 자바다/08 인터페이스

8.5 디폴트 메소드

빌드이너프 2024. 4. 3. 09:25

인터페이스에는 완전한 실행 코드를 가진 디폴트 메소드를 선언할 수 있다

 

추상 메소드는 실행부(중괄호{})가 없지만, 디폴트 메소드에는 실행부가 있다

public default 리턴타입 메소드명(매개변수, ...) { ... }

 

 

예제

package ch08.sec05;

public interface RemoteControl {
	int MAX_VOLUME = 10;
	int MIN_VOLUME = 0;
	
	void turnOn();
	void turnOff();
	void setVolume(int volume);
	
	default void setMute(boolean mute) {
		if(mute) {
			System.out.println("무음");
			setVolume(MIN_VOLUME);
		} else {
			System.out.println("무음 해제");
		}
	}
}
package ch08.sec05;

public class Television implements RemoteControl {

	private int volume;

	@Override
	public void turnOn() {
		System.out.println("Tv를 켭니다");
	}

	@Override
	public void turnOff() {
		System.out.println("Tv를 끕니다");
	}

	@Override
	public void setVolume(int volume) {
		if(volume > RemoteControl.MAX_VOLUME) {
			this.volume = RemoteControl.MAX_VOLUME;
		} else if(volume < RemoteControl.MIN_VOLUME) {
			this.volume = RemoteControl.MIN_VOLUME;
		} else {
			this.volume = volume;
		}
		System.out.println("현재 볼륨: " + this.volume);
	}


}

 

디폴트 메소드는 구현 객체가 필요한 메소드

RemoteControl의 setMute() 메소드를 호출하려면 구현 객체인 Television 객체를 인터페이스 변수에 대입하고 나서 setMute()를 호출해야 한다

package ch08.sec05;

public class RemoteControlExample {
	public static void main(String[] args) {
		RemoteControl rc = new Television();
		
		rc.setMute(true);
		rc.setMute(false);
	}
}

 

 

구현 클래스는 디폴트 메소드를 재정의해서 자신에게 맞게 수정할 수도 있다

재정의 시 주의할 점

public 접근 제한자를 반드시 붙여야 하고, default 키워드를 생략해야 한다