What do you call the superclass and subclass when initializing? [duplicate]

若如初见. 提交于 2019-12-20 07:57:09

问题


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

What is List and ArrayList when identifying the parts besides super class and subclass?

Is List the reference and ArrayList the class?

Would they be called something else if they were the same like:

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

回答1:


List is an interface. ArrayList is an implementation of it. Neither is a superclass or subclass of the other.




回答2:


There are three parts to this declaration:

  1. A named reference (list)
  2. The compile time, static type of the reference (List<String>)
  3. The run time, dynamic type of the reference (ArrayList<String>)

Each of those pieces would retain their character regardless of how you modified the compile time type.

List is an interface; ArrayList is an implementation of that interface.




回答3:


In the first example List is the interface which defines the type of reference to the object list and ArrayList is the implementation of the interface which is the type of the actual object. In the second example, both object and its reference have type ArrayList




回答4:


Difference:

  • First one, Only methods of the interface List can be invoked on the list object. polymorphisme is present here.
  • Second one, methods of ArrayList class can be invoked on the list object.

Advantages of the first one:

Even if you change the implementation to:

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

or

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

You have not to change the rest your code.



来源:https://stackoverflow.com/questions/35135019/what-do-you-call-the-superclass-and-subclass-when-initializing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!