I have come across some java classes used in the spring framework. First, there is the beans in the applicationContext.xml
<bean id="someBean" parent="txProxyTemplate">
<property name="target">
<bean class="path.to.bean.impl.SomeBeanImpl">
...
</bean>
...
</bean>
And I have the interface ISomeBean, and its implementation SomeBeanImpl
Then, I have another class which uses ISomeBean.
public class SomeOtherClass {
...
public function doStuff() {
...
ApplicationContext ctx;
SomeBean theBean = (SomeBean) ctx.getBean;
}
}
I want to know why do we cast to an interface instead of casting to the class.
Why would you want to tie
SomeOtherClassto a specific implementation? Using the interface, you get loose coupling – you can test against a fake implementation, or switch to a different implementation later.This is a large part of the benefit of inversion of control – you aren’t as tightly coupled to your dependencies as if you instantiate them directly within the class.