Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why cast to an interface instead of casting to a class java?

Tags:

java

spring

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.

like image 921
Mansuro Avatar asked Dec 28 '25 16:12

Mansuro


2 Answers

Why would you want to tie SomeOtherClass to 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.

like image 164
Jon Skeet Avatar answered Dec 31 '25 09:12

Jon Skeet


The logic behind such type of casting is to give freedom to the Spring IOC and Dependency Injection. One of the benefits of using this approach is that the coupling between classes is very loose,

for example in ur case if some fine morning u decide to change the code of ISomeBeanImpl, u don't need to change anything else as long as functionality doesn't change..

Have a look on Spring IOC documentation, the idea will be more clear...

like image 39
Amit Avatar answered Dec 31 '25 07:12

Amit