아래에는 Person 클래스, 구현 클래스 및 Person 클래스를 초기화하고 다시 출력하는 드라이버 클래스가 있습니다.인터페이스 대 콘크리트 클래스
Person person = new PersonImpl();
대신
PersonImpl person = new PersonImpl();
의 인터페이스 구현을 숨기고하도록되어 사용의 장점은 무엇입니까? 이것이 인터페이스를 사용하는 올바른 방법입니까?
public class Driver {
public static void main(String [] args)
{
Person person = new PersonImpl();
person.setName("test name");
System.out.println("Name is "+person.getName());
}
}
public interface Person {
public void setName(String name);
public String getName();
}
public class PersonImpl implements Person{
private String name;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
그래, 괜찮 았어. –
고맙지 만, 완전히 이해하지 못하고, 더 큰 그림을 보지 못했을 것이다. 왜 PersonImpl person = new PersonImpl(); person.setName "test name"); System.out.println ("Name is"+ person.getName()); – user701254
물론 사람 유형이 한 가지만 있다고 예상하면 인터페이스가 전혀 필요 없습니다. 'Person' 클래스를 직접 구현할 수 있습니다. 이는 특히 동일한 서브 시스템 또는 모듈 *에있는 코드에 해당됩니다. 일반적으로 다른 패키지에서 볼 수있는 클래스에 대한 인터페이스를 정의하는 것이 좋습니다. –