Suppose I have a method called " meuMetodo()
" that returns an Object of type ArrayList<String>
, I can make this method declare that it returns more concrete or more abstract types:
public ArrayList<String> meuMetodo() {...}
public List<String> meuMetodo() {...}
public Collection<String> meuMetodo() {...}
public Object meuMetodo() {...}
- Is there a "good practice" convention on which Type to declare as a return for each context ?
- What are the advantages, disadvantages, and limitations of declaring a more abstract Type? (such as List, Collection, or even Object)
- What are the advantages, disadvantages, and limitations of declaring a more concrete Type? (in this example, the most concrete would be the ArrayList)
I want a canonical response that takes into account things like:
- It makes a difference if the method in question will be overwritten by a Subclass in the future (I lose flexibility when extending depending on what I declare as Return Type)?
- It is important to consider what Customers of this method (the codes that will call it) require the returned Object (for example, the methods they will call on the returned Object)?
- Is it important to consider for which methods the Returned Object will be sent as an argument?