user8656194 user8656194 - 3 years ago 181
Java Question

Methods That Return an Object of an Interface Type

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 ?

Answer Source

"...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:

  • It is possible to change implementation of the method to return another object that implements the same interface, without changing code that uses this method.
  • You leave possibility for extending classes to override the method, so that it returns another object that implements the same interface. Here you can actually change the return type. If method of the base class returned concrete class, e.g., 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download