Reputation: 637
As a C++ oldtimer I have managed to solve my problem but I can not wrap my head around the underlying Java mechanisms here:
Vector<Object> x = new Vector<Object>(); // OK
ArrayList<Object> y = new ArrayList<Object>(); // OK
List<Object> zzz = new ArrayList<Object>(); // OK solves problem below but question remains
List<Object> z = new List<Object>(); // WHY? Compiler error: Cannot instantiate
Upvotes: 9
Views: 8036
Reputation: 424
Yes. Because List is an Interface and in Java you cannot instantiate an Interface. You can only instantiate a class.
ArrayList is a class that's implementing List<> that's why you can instantiate it. :)
Upvotes: 3
Reputation: 13882
List
is an interface
and an interface can't be instantiated.
It's used to implement polymorphism. i.e. a reference of interface type can hold object of any class that implements
it.
List<Object> zzz = new ArrayList<Object>();
it works, cause ArrayList implements List.
Upvotes: 0
Reputation: 17923
The List
is an interface. You cannot create in instance of an interface using new
operator. That's why the line List<Object> z = new List<Object>();
gives error. Only classes can be instantiated.
Upvotes: 2
Reputation: 30855
List isn't class it's an Interface and you can't instantiate the interface object.
ArrayList is the class which was implement the List interface so can able to instantiate the ArrayList object and assign to the List object
Upvotes: 1
Reputation: 137442
List is an interface, you cannot initialize it. ArrayList
implements List
, so you can assign an ArrayList
instance to a List
variable.
Upvotes: 5
Reputation: 116764
List
is an interface, somewhat like a class with some = 0
methods in C++. You can't instantiate it.
But ArrayList<T>
"inherits" List<T>
(or in Java terms, implements it), so those references are assignment-compatible.
Upvotes: 15