7
Suppose I have a method called "meuMetodo()
" that returns an Object of Type ArrayList<String>
, i can make this method declare that returns more concrete or more abstract types:
public ArrayList<String> meuMetodo() {...}
public List<String> meuMetodo() {...}
public Collection<String> meuMetodo() {...}
public Object meuMetodo() {...}
- Is there any "good practice" convention on which type to declare as return for each context?
- What are the advantages, disadvantages and limitations of declaring a more abstract type as return? (like List, Collection, or even Object)
- What are the advantages, disadvantages and limitations of declaring a more concrete type as return? (in this example, the most concrete would be the Arraylist)
I wish for 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 to the extend depending on what I declare as Return Type)?
- It is important to consider what the Clients of this method (the codes that will call it) need from the returned Object (for example, the methods they will call in the returned Object)?
- It is important to consider for which methods the returned object will be sent as argument?