Interface Pros
변경에 유리하며 유연한 코드가 된다.
-두 대상(객체) 간의 '연결,대화,소통'을 돕는 중간 역할을 한다.
-선언(설계, 껍데기)와 구현(알맹이)을 분리시킬 수 있게 한다.
ex) 강한 결합, 변경에 불리
class B {
public void method() {
System.out.println("methodInB");
}
}
ex) 인터페이스를 이용한 느슨한 결합, 변경에 용이
interface I {
public void method();
}
class B implements I {
public void method() {
System.out.println("methondInB");
}
}

사용자는 자판기를 사용한다. 자판기의 내용물(음료수/과자/샐러드 등)이 바뀐다.
class A {
public void method(I i) {
i.methodB();
}
}
//선언부와 구현을 분리.(껍데기와 알맹이를 분리하여 사용한다.)
//1. 메서드 선언(껍데기)
interface I{public abstract void method();}
//2. 메서드 구현(알맹이)
class B implements I {
public void method() {
System.out.println("B클래스의 메서드 in interface I");
}
}
class C implements I {
public void method() {
System.out.println("C클래스의 메서드 in interface I");
}
}
//main
public class InterfaceTest {
public static void main(String[] args) {
A a = new A();
//class A does not need to modify code.
a.method(new B());
a.method(new C());
//C c = new C();
//a.method(c);
}
}
2. 개발 시간을 단축할 수 있다. A->I(B).
A는 B가 완성될 때까지 기다리지 않고도 코드를 작성할 수 있다. B를 구현하지 않아도 Interface I 안에 B가 있다면 인터페이스(I)는 추상메서드의 집합이고 껍데기이다. 추상메서드 B를 구현하면 된다.
Q. iv는 어떻게 사용할 수 있는가?
A. (캡슐화)iv 직접 접근은 불가하며 private 제어자를 통해 메서드를 통해서만 접근할 수 있도록 한다. .
3. 변경에 유리한 유연한 설계가 가능하다. A->I(B), A->I(C), A->I(D)
4. 표준화가 가능하다. Java Application->JDBC(인터페이스 집합)->Oracle_DB , Java Application->JDBC->MySQL_DB
추후 JSP나 Spring을 배우면 JDBC를 다루게 된다.
5. 서로 관계없는 클래스들을 관계를 맺어줄 수 있다.
상속 계층도에서 공통점을 찾기 어려울 때, 공통적인 부분들을 골라서 인터페이스를 구현하게 한다.

//multiple overloading
void repair(Tank t) {...}
void repair(SCV s) {...}
void repair(Dropship d) {...}

//parameter is the class which implments Repairable interface
void repair(Repairable r) {
if(r instanceof Unit) {//instanceof : check casting
Unit u = (Unit)r;
while(u.hitPoint != u.MAX_HP) {
u.hitPoint++;//Unit의 HP를 증가시킨다.
}
}
}
interface Repairable {}
class SCV extends GroupUnit implements Repairable {...}
class Tank extends GroupUnit implements Repairable {...}
class Dropship extends AirUnit implements Repairable {...}
Last updated
Was this helpful?