0

I've seen many times statements like this:

List list = new ArrayList<String>();

What's the point of writing like this? I mean setting the type of object a super class or implemented Interface of it. Is this makes a difference or improves performance or things like that?

Note

My English is poor and I've probably written the question title and body confusing. Please edit that and then remove this line.

Alireza Farahani
  • 2,238
  • 3
  • 30
  • 54

1 Answers1

0

That statement means that you can use all of the features of List that are implemented using ArrayList but you could also use the features inside LinkedList. Although there is no harm if you have the object type as ArrayList, it could be useful for example, if you have a method that takes in a List parameter instead of an ArrayList, your choices have expanded and you can have other classes that implement that type, e.g LinkedList.

To put it simply, if you are using the interface List as its type, you are saying: "I want to use any class that does these things to do my own" as List is an interface. But if you just use ArrayList, you are saying: "I want to use just this specific class to to my things". In summary, it gives you more flexibility.

Other than that, there isn't much of a difference using the super class as the type or using ArrayList or other subclass as itself.

Hope that this is what you are asking about, and hope that it makes sense. If not, feel free to ask any questions.

Arbiter
  • 433
  • 2
  • 9