01. 인터페이스란
- 객체의 사용 방법을 정의한 타입
- class 키워드 대신 interface 키워드가 붙으며, 인터페이스를 구현하는 클래스는 implements 키워드를 사용함
- 개발코드와 객체가 서로 통신하는 접점이다.
: 개발코드가 인터페이스의 메소드 호출 >> 인터페이스가 객체의 메소드 호출
- 인터페이스가 중간 역할을 해 주기 때문에 개발 코드는 객체의 내부 구조를 알 필요가 없다 --> 개발코드를 수정하지 않고도 사용하는 객체를 변경할 수 있다.
1
2
3
4
5
6
7
8
9
10
|
interface 인터페이스명 {
//상수
타입 상수명 = 값;
//추상 메소드 - 무조건 오버라이딩 필요... 번거롭다.
타입 메소드명(매개변수,...);
//디폴트 메소드 - 인터페이스에 선언되었으나 구현객체를 통해서만 사용할 수 있다. 그대로 써도 되고 오버라이드 해도 된다. 확장이 용이하고 더 유연하다.
default 타입 메소드명(매개변수, ...) {...}
//정적 메소드 - 인터페이스명을 통해서만 접근할 수 있다. (인터페이스명.메소드명();)
static 타입 메소드명(매개변수,...){...}
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
|
02. 인터페이스의 구성
- 인터페이스는 객체로 생성할 수 없기 때문에 생성자를 가질 수 없다 (=상수와 메소드만으로 구성되어 있다)
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
|
public interface RemoteControl {
//상수 선언
public int MAX_VOLUME = 10;
public int MIN_VOLUME = 0;
//추상 메소드
public void turnOn();
public void turnOff();
public void setVolume(int volume);
//디폴트 메소드
default void setMute(boolean mute) {
if(mute) {
System.out.println("무음 처리합니다");
} else {
System.out.println("무음 해제합니다");
}
} //setMute();
//정적 메소드 (static은 저절로 public)
static void changeBattery() {
System.out.println("건전지를 교환합니다");
}
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
|
03. 다중인터페이스 구현 클래스
- 하나의 클래스가 여러개의 인터페이스를 구현하는 것도 가능하다. 인터페이스명을 컴마로 나열해주면 된다.
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
31
32
33
34
35
36
37
38
39
|
public class SmartTelevision implements RemoteControl, Searchable {
private int volume;
//searchable의 추상메소드
@Override
public void search(String url) {
System.out.println(url + "을 검색합니다.");
}
//RemoteControl의 추상메소드
@Override
public void turnOn() {
// TODO Auto-generated method stub
System.out.println("TV를 켭니다");
}
@Override
public void turnOff() {
// TODO Auto-generated method stub
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("현재 TV 볼륨 : " + this.volume);
}// setVolume();
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
|
04. 디폴트 메소드의 필요성
- 어떤 인터페이스를 구현한 classA가 있다.
- 그 인터페이스에는 추상메소드A가 있으며, classA는 methodA를 오버라이딩 하고 있다.
- 인터페이스에 새로운 메소드인 methodB를 추가하려고 한다.
- 이 때, methodB를 추상메소드로 선언하게 되면 classA에는 해당 메소드의 실체 부분이 없으므로 문제가 생긴다.
- methodB를 default method로 선언하면, 구현클래스에서 실체 메소드를 작성할 필요가 없으므로 A클래스는 수정할 필요가 없다.
- 이렇게 methodB를 추가한 인터페이스를 새로운 클래스 B에서 구현한다.
- 기존에 가지고 있던 클래스A의 수정 없이 새로운 기능 추가가 가능해졌다.