Ch7-39. 인터페이스 장점
0. 목차
Chapter7. 객체지향 프로그래밍Ⅱ
Ch7 - 39. 인터페이스 장점
Ch7 - 39. 인터페이스 장점
▶ 인터페이스(interface)의 장점
▷ interface : inter(~사이) + face(얼굴)
▷ 두 대상(객체) 간의 연결, 대화, 소통을 돕는 ‘중간 역할’
▷ 변경에 유리 : 선언(껍데기)과 구현(알맹이) 분리 가능
- 인터페이스 덕분에 C가 변경 되어도 A는 바뀌지 않아도 됨 : 느슨한 결합
▷ 개발 시간을 단축
▷ 표준화 가능
▷ 서로 관계없는 클래스들을 관계를 맺어줄 수 있음
▶ 실습
▷ 인터페이스 사용하지 않고 클래스 A가 클래스 B를 사용
class A {
public void method(B b) {
b.method();
}
}
class B {
public void method() {
System.out.println("method B");
}
}
class Test {
public static void main(String[] args) {
A a = new A();
a.method(new B());
}
}
// console
method B
▷ 인터페이스 사용하지 않고 클래스 A가 클래스 C를 사용
▷ 어디가 달라졌나?
class A {
public void method(C c) { // 매개변수 C로 변경
c.method();
}
}
class B {
public void method() {
System.out.println("method B");
}
}
class C { // 클래스 C 생성
public void method() {
System.out.println("method C");
}
}
class Test {
public static void main(String[] args) {
A a = new A();
a.method(new C()); // 클래스 C 객체 생성 해 주기
}
}
// console
method C
▷ 인터페이스 사용하여 클래스 A가 클래스 B를 사용
class A {
public void method(I i) { // 매개변수 : I를 구현한 애들만 와라
i.method();
}
}
interface I { // 메서드 선언부만 있음
void method();
}
class B implements I { // I implements
public void method() { // 구현부 완성
System.out.println("I구현 : 클래스B'method");
}
}
class Test {
public static void main(String[] args) {
A a = new A();
a.method(new B());
}
}
// consoel
I구현 : 클래스B'method
▷ 인터페이스 사용하여 클래스 A가 클래스 C를 사용
▷ 어디가 달라졌나?
package baek;
class A {
public void method(I i) {
i.method();
}
}
interface I {
void method();
}
class B implements I {
public void method() {
System.out.println("I구현 : 클래스B'method");
}
}
class C implements I { // 여기
public void method() {
System.out.println("I구현 : 클래스C'method");
}
}
class Test {
public static void main(String[] args) {
A a = new A();
a.method(new C()); // 여기
}
}
// console
I구현 : 클래스C'method