All beginners like myself, always get confused to see a method returns an object of an interface type, because interfaces have abstract methods, thus cannot be instantiated.
I finally figured out a way to understand this:
((when we say that a method returns an object of an interface type, we are actually implicitly saying that the method in fact returns an object/instance of some class that implements that interface, but in most cases that class is unknown because it is declared as anonymous in the implementation of the method. Thus, we refer to the returned object as being of that interface type.)).
Is this explanation correct ?
"...when we say that a method returns an object of an interface type, we are actually implicitly saying that the method in fact returns an object/instance of some class that implements that interface..." - It is correct, but we are saying it explicitly.
The second part of your definition is quite not correct, as @Jon Skeet pointed out. Applying anonymous class in the implementation is a very specific case. Generally, returning an interface gives you more freedom:
ArrayList
, overridden method would have to also return ArrayList
or its subclass.The rule of thumb is the following. If concrete class implements an interface and there is no benefit in returning a concrete class object, e.g., ArrayList
, return an interface - List
, Collection
. This will enhance maintainability of your code, i.e., the code will be easier to change in future.