My footsteps
인터페이스 사용 이유 본문
728x90
class AA{
public void method(BB b) {
b.method();
}
}//BB의 매서드를 호출하는 매서드
class BB{
public void method() {
System.out.println("BB클래스의 매서드");
}
}
public class JangRi {
public static void main(String[] args) {
AA a = new AA();
a.method(new BB()); //BB객체를 만들어서 넣음
//AA객체가 BB객체를 사용해서 BB매서드 호출(=의존)
}
}
이런 코드에서 새로운 클래스를 추가하면 호출부분들을 다 바꿔야 하는 번거로움이 있는데
인터페이스로 선언부와 구현부를 나눠준다면,
▼
class AA{
public void method(I i) {
i.method();
}
}//인터페이스 I를 구현한(=만든)넘들만 들어와라
interface I{
public void method(); //선언부
}
class BB implements I{ //구현부
public void method() {
System.out.println("BB클래스의 매서드");
}
}
public class JangRi {
public static void main(String[] args) {
AA a = new AA();
a.method(new BB()); //BB객체를 만들어서 넣음
//AA객체가 BB객체를 사용해서 BB매서드 호출(=의존)
}
}
변경하는 번거로움을 많이 줄일수 있음
728x90
'예습 > code' 카테고리의 다른 글
Math.random,for문 (0) | 2023.01.15 |
---|---|
if 조건식,if-else문,else if,switch문 (0) | 2023.01.14 |
인터페이스의 다형성 (0) | 2023.01.14 |
추상클래스 (0) | 2023.01.14 |
여러 종류의 객체를 배열로 다루기 (0) | 2023.01.13 |