Reputation: 19474
If you have one interface called A that has one method signature called print; Now if you have 3 classes implementing A and you call A.print how do you know which class method gets invoked. THERE IS NO NEWING OF AN OBJECT
public interface A()
{
public void print(){}
}
@Component
public class B implements A
{
public void print()
{
system.out.print("B");
}
}
@Component
public class c implements A
{
public void print()
{
system.out.print("C");
}
}
@Component
public class d implements A
{
public void print()
{
system.out.print("d");
}
}
public class runner()
{
@Autowired
private A aThing_;
aThing_.print();
}
Upvotes: 1
Views: 213
Reputation: 10055
An interface defines an interaction contract or, in other words, defines a set of methods that every class implementing that interface should provide.
Oracle's answer to the question, What's an Interface? is:
As you've already learned, objects define their interaction with the outside world through the methods that they expose. Methods form the object's interface with the outside world; the buttons on the front of your television set, for example, are the interface between you and the electrical wiring on the other side of its plastic casing. You press the "power" button to turn the television on and off.
The invocation depends on the type of the object implementing the interface.
A interface = new B();
You'll be invoking B
's print
method's implementation for the print
method defined in the A
interface.
EDIT: The point of an interface is defining the interaction with an object regardless of its actual type. That code seems to be the autoscanning of a group of components behind the same interface to show that you can define a set of different components to handle the same situation in a different way, given the context.
AFAIK the autowire defaults to the field's name. You can define which interface implementation you want to inject with the @Qualifier("CLASS_NAME_HERE")
annotation alongside with @Autowire
.
You might want to check this.
Upvotes: 3
Reputation: 4502
If I understand our example correctly, you have a class Runner, to which a reference to an object which implements A is autowired.
The whole point of the interface is polymorphism. In other words, the purpose of using the interface A in this design is so that Runner doesn't need to know which implementation is being used - all Runner cares about is that the method(s) defined on A are available.
You can set up a property on A which returns some sort of type information, but (with some exceptions, I believe) that defeats part of the purpose.
Upvotes: 0
Reputation: 9331
Depends on how you instantiate such Object:
For example
private A aThing = new C();
Will invoke C
print method
Upvotes: 0
Reputation: 240948
It will call the method version from the class whose object invokes it
A ob = new B();
ob.print()// will invoke method from B
A ob = new C();
ob.print()// will invoke method from C
See
Upvotes: 1