인터페이스의 장점
- 개발 시간 단축
- 변경에 유리한 유연한 설계 가능
- 표준화가 가능
- 서로 관계없는 클래스들을 관계 맺어줄 수 있음
선언과 구현 분리
1 | class B { |
2 | public void method() { |
3 | System.out.println("methodInB"); |
4 | } |
5 | } |
1 |
|
2 | interface I { |
3 | public void method(); |
4 | } |
5 |
|
6 |
|
7 | class B implements I { |
8 | public void method() { |
9 | System.out.println("methodinB"); |
10 | } |
11 | } |
예제)
- A가 B에 의존할 경우, 인터페이스 덕분에 B가 변경되어도 A는 안바꿀 수 있게 된다.(느슨한 결합)
- 변경에 유리함
![image](https://user-images.githubusercontent.com/53684676/95966583-4864d780-0e46-11eb-9f99-53835169b8d3.png)
개발 시간 단축
![image](https://user-images.githubusercontent.com/53684676/95969611-ea39f380-0e49-11eb-96ed-a03eece02572.png)
- A가 B를 사용하기 위해서 B가 완성될때까지 기다려야 함.
![image](https://user-images.githubusercontent.com/53684676/95969673-fde55a00-0e49-11eb-88b5-454846746501.png)
- A가 I를 사용함으로써 B가 개발 안됐어도 I를 호출(B가 완성됐다고 가정하고 개발)
- 캡슐화 / iv에 직접 접근하지 않고 method를 통해서 접근하기 때문에 상관없음
![image](https://user-images.githubusercontent.com/53684676/95971818-a8f71300-0e4c-11eb-9727-f45f14db3e94.png)
1 | void repair(Repairable r) { |
2 | if (r instanceof Unit) { |
3 | Unit u = (Unit)r; |
4 | while(u.hitPoint != u.MAX_HP){ |
5 | u.hitPoint++; |
6 | } |
7 | } |
8 | } |
사진, 그림: 자바의정석저자 [남궁성님 유투브강의](