问题
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:
- A named reference (
list) - The compile time, static type of the reference (
List<String>) - 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
Listcan be invoked on the list object. polymorphisme is present here. - Second one, methods of
ArrayListclass 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