Java/모두의 자바

Chapter 08-45 인터페이스의 default 메서드

계란💕 2022. 2. 11. 10:25

08-45.1 자바8이 등장하면서 바뀐 인터페이스 내용

 

  - 기존의 인터페이스는 추상 메서드만 가질 수 있었다

  - 자바 8부터는 defeult 메서드와 static메서드를 정의할 수 있다.

  - 인터페이스를 default로 선언하면  메서드로 구현할 수 있다. 

 

 

08-45.2 계산기 인터페이스 예제

 - 계산기 인터페이스를 구현해서 알아보자.

 

  (1) plus, multiple, exec 메서드를 추가한다.

<hide/>
package javaStudy;

public interface Calculator {
	public int plus(int i, int j);
	public int multiple(int i, int j);
	default int exec(int i, int j) {
		return i + j;
	}
}

  (2) multiple 메서드를 구현하기 위해 중괄호를 열면 에러가 발생한다.

<hide/>
package javaStudy;

public interface Calculator {
	public int plus(int i, int j);
	public int multiple(int i, int j) {
	}
	default int exec(int i, int j) {
		return i + j;
	}	
}

  Note) 실행 결과: Abstract methods do not specify a body.

  - 인터페이스는 원래 추상 메서드만 가질 수 있었기 떄문에 에러가 난다. 

  - 그런데 자바 8부터는 default라는 키워드를 붙여 메서드를 구현하는 기능을 추가했다. 

  - default를 붙이면 인터페이스도 구현한 메서드를 가질 수 있게 된다. 

  - 왜 이런 기능이 추가됐을까?

 

  (3) Calculator 인터페이스를 추가한 클래스를 만들고 두 메서드를 구현한다.

<hide/>
package javaStudy;

public class MyCal implements Calculator {
	@Override
	public int plus(int i, int j) {
		return i + j;
	}
	@Override
	public int multiple(int i, int j) {
		return i * j;
	}
}

 

  (4)  새로운 MyCalTest클래스를 만든다.

<hide/>
package javaStudy;

public class MyCalTest {
	public static void main(String[] args) {
		Calculator cal = new MyCal();
		cal.plus(3, 4);
		int i = cal.exec(5, 6);
		System.out.println(i);
	}
}

  Note) 실행 결과: 11

  - default 로 구현한 메서드는 정숫값을 리턴하므로 위 처럼 새로운 int 를 선언하여 출력할 수도 있다. 

  - Calculator 인터페이스에 구현한 대로 결과가 나온다. 

  - 자바 8에서 왜 default를 추가했을까?

    -> 인터페이스를 구현하는 모든 클래스는 해당 메서드를 모두 구현해야 한다. 

  - 그런데 만약 인터페이스를 변경하면?

    -> 변경할 인터페이스를 구현하는 모든 클래스가 다시 변경사항을 구현해야 한다.

    -> 바로 이런 문제를 해결하기 위해 인터페이승에서 메서드를 구현할 수 있도록 default를 추가한 것이다. 

 

 

08-45.3 static 키워드를 이용해서 인터페이스에 메서드를 구현하자.

<hide/>
package javaStudy;
public interface Calculator {
	public int plus(int i, int j);
	public int multiple(int i, int j);
	default int exec(int i, int j) {
		return i + j;
	}	
	public static int exec2(int i, int j) {
		return i * j;
	}
}
<hide/>
package javaStudy;
public class MyCalTest {
	public static void main(String[] args) {
		Calculator cal = new MyCal();
		cal.plus(3, 4);
		int i = cal.exec(5, 6);
		System.out.println(i);
		cal.exe2
	}
}

  Note) 실행결과

  - cal.를 입력해도 exec2라는 메서드는 나오지 않는다. cal.exec2를 입력했더니 에러가 난다. 

  - static메서드는  반드시 인터페이스명.메서드명.(); .. 형식으로만 호출해야 사용가능하다.

  - 즉, Calculator.exec2(); 형식으로만 사용가능하다.

<hide/>
package javaStudy;
public class MyCalTest {
	public static void main(String[] args) {
		Calculator cal = new MyCal();
		cal.plus(3, 4);
		int i = cal.exec(5, 6);
		System.out.println(i);
		Calculator.exec2(3, 4 );
	}
}

  - 이처럼 인터페이스에서 static 메서드를 사용하면 인터페이스를 사용해 간단한 기능을 가진 유틸리티설 인터페이스를 만들 수 있다.

 

 

08-45.4 인터페이스의 default 메서드 실습

 

  Ex) Taxi클래스는 Meter인터페이스를 구현한다. TaxiExam클래스를 실행했을 때 실행결과와 같은 결과가 나오도록 Meter인터페이스를 수정하라.

<hide/>
package javaStudy;
public interface Meter {
	public abstract void start();
	public abstract int stop(int distance);	
//정답  public default void afterMidnight() {
//	 	System.out.println("자정이 넘었습니다.할증이 필요한 경우 이 메서드를 오버라이드 하세요.");
//	}
}
<hide/>
package javaStudy;
public interface Meter {
	public abstract void start();
	public abstract int stop(int distance);	
  		public default void afterMidnight() {
  		System.out.println("자정이 넘었습니다.할증이 필요한 경우 이 메서드를 오버라이드 하세요.");
	}
}
<hide/>
package javaStudy;
public class TaxiExam {
	public static void main(String[] args) {
		Taxi taxi = new Taxi();
		taxi.start();
		taxi.afterMidnight();
		taxi.stop(10);	
	}
}

  Note) 실행 결과

  - Taxi 클래스에 afterMidnight라는 메서드가 존재하지 않는다.

  - 그런데, main메서드에서 사용하는 것으로 보아 Meter인터페이스에서 afterMidnight를  정의했다는 것을 알 수 있다.