Java/Java icia 19일차

Interface 예제

swkn 2023. 3. 20. 13:40
package classic;

public class ImplClass1 implements InterfaceEx{

	@Override
	public void hello() {
		System.out.println("ImplClass1.hello()");
	}
	
}

package classic;

public class ImplClass2 implements InterfaceEx{

	@Override
	public void hello() {
		System.out.println("ImplClass2.hello()");
		
	}

}
package classic;

public class InterfaceMain {

	public static void main(String[] args) {
		// 인터페이스 객체 생성 ( X )
//		InterfaceEx if1 = new InterfaceEx();
		
		// 아래와 같은 방식으로는 잘 사용하지 않는다 ( 인터페이스 쓰는 이유 없음 )
		ImplClass1 ipc1 = new ImplClass1();
		
		
		/* */ //설명할때 쓰는 주석 메모 등

		/** 메소드를 설명할때 쓰는 주석
		 * 좌변 : 인터페이스 타입의 객체로 선언 
		 * 우변 : 구현클래스 생성자
		 */
		InterfaceEx if1 = new ImplClass1();
		if1.hello();
		
		InterfaceEx if2= new ImplClass2();
		if2.hello();
		
		InterfaceEx if3 = new ImplClass1();
		if3.hello(); // implclass1 호출
		if3 = new ImplClass2(); // 기존 객체에 implclass2 호출
		if3.hello(); // implclass2 생성자 사용
		// 이문구에서 다형성을 확실하게 사용
	}

}

출력물

ImplClass1.hello()
ImplClass2.hello()
ImplClass1.hello()
ImplClass2.hello()