Altair827 Altair827 - 1 year ago 94
Java Question

Why this declaration is correct in Java

I am new to Java and I have a huge confusion here. How is this possible

List<String> list = new ArrayList<String>();

List is an interface and how it can have a ArrayList which is a class.

Answer Source

The type of a variable and the type of the object the variable refers to do not need to be the same, so long as the type of the object is compatible with the type of the variable. So what does it mean to be compatible?

It means that the object's type has an "is a" relationship with the variable's type. ArrayList<String> "is a" List<String>, because ArrayList implements the List interface. That is, ArrayList has all of the methods that List defines, and declares (by saying implements List) that it conforms to the definition of those methods.

This is a fundamental concept in object-oriented programming called polymorphism. That is, we can say that there is a thing called a List, and we can write code that works with Lists, without that code knowing that the actual Lists it's working with are ArrayLists or LinkedLists or any other concrete type.

In this case, it's with an interface, but the same concept applies in object type hierarchies as well. If you have class Animal, you might have a more specific subclass (Dog). Anything that works with the Animal type can work with Dogs, because Dog is an Animal.

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