class A{
public void method(B b) {
b.method();
}
}
class B{
public void method() {
System.out.println("B클래스의 메서드 ");
}
}
public class InterfaceTest {
public static void main(String[] args) {
A a = new A();
a.method(new B()); // A가 B를 사용(의존)
}
}
→ 클래스 C 추가. 이제 B를 안쓰고 C를 쓸려고 한다.
class A{
public void method(B b) {
b.method();
}
}
class B{
public void method() {
System.out.println("B클래스의 메서드 ");
}
}
public class InterfaceTest {
public static void main(String[] args) {
A a = new A();
a.method(new C()); // A가 C를 사용(의존) //=> 변경부분
}
}
→ B말고 C를 의존하도록 변경함
⇒ 에러표시와 함께 run시켜보면 에러가남
why?
A클래스 method(B b) 부분에 매개변수도 B b가 아니라 C b 이렇게 변경해줘야함.
class A{
public void method(C b) {
b.method();
}
}
class B{
public void method() {
System.out.println("B클래스의 메서드 ");
}
}
class C{
public void method() {
System.out.println("C클래스의 메서드 ");
}
}
public class InterfaceTest {
public static void main(String[] args) {
A a = new A();
a.method(new C()); // A가 B를 사용(의존)
}
}
위와 같이 하면 불편함을 느낀다. 알맹이를 변경하는데 2번의 수정이 필요함.
코드를 다음과 변경한다면?
class A{
public void method(I i) {
i.method();
}
}
// B클래스의 선언과 구현을 분
interface I{
public void method();
}
class B implements I{
public void method() {
System.out.println("B클래스의 메서드 ");
}
}
class C{
public void method() {
System.out.println("C클래스의 메서드 ");
}
}
public class InterfaceTest {
public static void main(String[] args) {
A a = new A();
a.method(new B()); // A가 B를 사용(의존)
}
}
→ a.method(new B()); 가 아닌 C를 넣을려면
class A{
public void method(I i) {
i.method();
}
}
// B클래스의 선언과 구현을 분
interface I{
public void method();
}
class B implements I{
public void method() {
System.out.println("B클래스의 메서드 ");
}
}
class C implements I{
public void method() {
System.out.println("C클래스의 메서드 ");
}
}
public class InterfaceTest {
public static void main(String[] args) {
A a = new A();
a.method(new C()); // A가 B를 사용(의존)
}
}