I’d like to know how can I declare a method will return an instance of a specific class.
For example:
The abstract class A declares a method (method1) that must return a instance of “List”
the class B and C extends A. I want B to return an ArrayList and C to return a LinkedList.
How can I implement that? Thanks
If you want the caller to know that it’s getting a
LinkedListorArrayListthen you can leverage generics.It would look something like this:
Or, if you are going to be interacting with
BandCdirectly (not viaA) then you can leverage covariant return types and simply have the subclasses declare the return type asArrayListandLinkedListrespectively. It is legal in Java 5+ to narrow the return type of an overridden method.If the concrete type doesn’t need to be known to the caller, then you just want to pass a strategy (i.e. a factory) for creating the list to
A. This can be done by implementing a simple interface:and then passing it to the constructor of
A. In fact, the factory can be used either way, however you only need classesBandCif you are in the first situation I described.