Issue
Let's say we have an interface as "ABC.java"
interface ABC {
public void hello();
}
Now we have a class like "ABCimpl.java"
public class ABCimpl implements ABC{
@Override
public void hello(){
System.out.println("Hello World!");
}
}
Now we have one more class named "DEFinpl.java"
public class DEFimpl{
@Autowired
ABC abc;
public void trial(){
abc.hello();
}
}
but if we are simply using java we do not create an object for an interface. Why is that? And what is happening here?
Solution
We cannot create an object of an interface in Java.
Interfaces in java can be defined as a full abstract class with fields (public , static & final) and empty methods (public and abstract). Although from Java 8 we can define default methods which can have their body and in Java 9 we can even have private methods.
But the point is , in an interface we don't have fields present at the object level since all of them are by-default static. Hence its not logical or meaningful to have a constructor
which means --> No object creation.
When we use spring @Autowired for initializing an interface , spring does not actually create an object of that interface rather an object of its child class is created.
In this case since only one child class exists for interface ABC which is class ABCImpl.
So Spring will do something like this when we use @Autowired :
ABC abc = new AbcImpl();
The abc is just a reference variable storing the object of child class (one of interface ABC implementation). Things get interesting if we have multiple child classes and we use @Autowired. Then spring resolves this ambiguity by first checking the type and then name. If both are same then we can go for something like @Qualifier to add some additional tag to differentiate it.
Answered By - ALS