An interface is never a variable, interface is interface, if you want to generalize the term, it is a guy since, yes, it indicates a contract. In Java 8 it even allows to have something beyond the contract, but I imagine that is not the case here.
It is possible declare a variable being of a kind interface
no problem, but concretely you can only assign a concrete type, i.e., a class (in other languages, or newer version of Java, can even do other things). Obviously the class that is used to instantiate a concrete object needs to be compatible with the declared interface, so be a type that implements the interface.
So this method used there should return a concrete object that is compliant with the interface NodeList
.
In the case of the variable noList
can only access members present in the interface (which the object certainly has, by the conformity established in the class). To access other members of the concrete object, just making one cast in the object. The interface has no knowledge about the other members.
It may be that the declared return of the method is an interface, but the actual return will be a concrete object that conforms to the interface of its return. Obviously if this interface is not NodeList
, shall be another which complies with NodeList
(derived from her).
Imagining that this would be the method documenting then the type returned is NodeList
. Signature of it:
NodeList getElementsByTagName(String name)
There lists the class IOMetadataNode
as a class that implements it. So possibly the method getElementsByTagName()
returns a concrete object of this class. But it can be something else, nothing guarantees it, it can even change a day and that "is not your concern" (the use of the interface says this).
How do I know which is the concrete object that returns from the class if it is not in the documentation? I have to look at the sources of this method?
In fact the idea of using the interface is precisely not need to think about the concrete type. It is not your interest to know, use the interface and ready. In many rare cases knowing the type will be useful and will probably do some gambiarra with this information. In general we program for the interface and not for the implementation.
There are some confusions there, I’ll try to explain, but I don’t even know where to start yet. Exactly what is returned by this method?
– Maniero
From what I understood from the code, the purpose has still remained, will only accept if the data type passed to noList is "signed" the contract, ie if implement
NodeList
. You are restricting that all data passed to this variable, regardless of type, meet what was displayed in the interfaceNodeList
. In the end, the purpose is the same.– user28595
If I understand correctly, when you do
NodeList noList = algo ...
are you saying thatnoList
receives something is a super type. Remember that vc can specify a super type(interface or abstract class usually) in method parameters.– rray