HashSet<T> theSet = new HashSet<T>();
Collection<T> collection = theSet;
Iterable<T> iterable = theSet;
Object object = theSet;
All of these four variables are of different types (all of them have to be super types of HashSet
by the way), but all of them refer to the same object whose type is HashSet
. No matter what variable you use to access the object, it will always behave in the same way. This is one of the key features of polymorphism.
The only difference is that the higher you move the inheritance tree (up means towards more general types), the less methods and fields are accessible for you. So you cannot call methods such as object.iterator()
, iterable.size()
etc., but when you call a method common for all the variables, it always behaves the same way:
theSet.toString(); // produces []
collection.toString(); // produces []
iterable.toString() // produces []
object.toString(); // produces []