简体   繁体   中英

Java - Type vs instance type

When I do something like:

List<Integer> myList = new LinkedList<>();

Is the object "myList" of type List? I am more interested about the correct definition. Would it be correct to say that:

myLyst is of type List but its instance is of type LinkedList?

That doesn't make sense to me because the object can be only one type. So maybe it would be better to say that it is of type LinkedList but restricted to the interface List?

myList has a concrete runtime class, and that is LinkedList .

But LinkedList as a type, is a subtype of List , so it is also correct to say that myList is a List .

The thing that is definite at runtime is that an object has only one runtime class, which in this case is LinkedList . This class can be read by calling myList.getClass() .

But checking type hierarchies, ie, whether an object is an instance of a given type (class or interface), doesn't require that the type it's being checked against is a class. So:

myList instanceof LinkedList //true
myList instanceof List //true
myList instanceof Collection //true
myList instanceof ArrayList //false, 
  //because it's not an instance of ArrayList, 
  //and LinkedList is not a subtype of ArrayList

The LinkedList class implements the List interface. myList is an instance of the LinkedList class and is therefore of type LinkedList .

Since an interface is not a type, myList is not of type List , as List , an interface, is not a type.

I hope this answer should clear some things up?

I would say that the static type of the variable is List and its runtime type is LinkedList.

This is obviously made possible by the fact that LinkedList implements List.

The distinction is important when discussing overriding (inheritance and virtual calls) and overloading (different methods with different parameters — parameters only take the static type into account)

Java List is an interface that extends Collection interface. Pic shows the hierarchy

Now, correct way would be, to say that "myList" is an interface variable currently holding the instance of LinkedList class. You can look it from another analogy as well, interface is just an abstract representation therefore we can never create an object of type List thus it can only be used to hold reference of object of the class that implements it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM