인터페이스 사용하는 이유를 살펴볼게요
MainClass.java
package com.javalec.ex;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
public class MainClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
AbstractApplicationContext ctx = new GenericXmlApplicationContext("classpath:applicationCTX.xml");
Pencil pencil = ctx.getBean("pencil",Pencil.class);
pencil.use();
ctx.close();
}
}
GenericXmlApplicationContext("xml파일명")
.xml 에서 읽어온 객체로 인터페이스 Pencil 에서 오버라이딩된 메소드를 호출하게 됩니다.
Pencil.java
package com.javalec.ex;
public interface Pencil {
public void use();
}
인터페이스 입니다
package com.javalec.ex;
public class Pencil4B implements Pencil {
public void use() {
System.out.println("4B 굵기로 쓰입니다");
}
}
Pencil에게 상속받은 클래스 이고 메소드를 오버라이딩 했습니다.
package com.javalec.ex;
public class Pencil6B implements Pencil {
public void use() {
System.out.println("6B 굵기로 쓰입니다");
}
}
Pencil6B 클래스로 Pencil 에게 오버라이딩한 use 메소드가 있습니다
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="pencil" class="com.javalec.ex.Pencil6B"/>
</beans>
Pencil6B 클래스로 pencil 객체를 가지고 있습니다.
MainClass 에서 java를 실행시키면 getBean()에 있는 객체는 Pencil6B 를 가리킵니다. pencil.use()는 Pencil6B 에 있는 출력문을 출력합니다