9

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 

7 Answers 7

15

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@Adam - wait till you get on to wildcards in Java generics! :) The answers take a little longer to appear.
Yeah Daniel, I have seen the wonderful little ibm.com/developerworks/java/library/j-jtp01255/index.html Anyway your answer was very much to the point and I DO know java interfaces just didnt think of List<> in those terms :)
5

List is an interface, you cannot initialize it. ArrayList implements List, so you can assign an ArrayList instance to a List variable.

Comments

3

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. :)

Comments

2

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.

Comments

1

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

Comments

1

"Interface" is like a protocol that an object must comply with.

3 Comments

Interesting approach to use protocols as an analogy. Although a little bit more text what "it" is and what not might things a little clearer.
I never heard protocol in this context. But I understand what you mean. I prefer the term contract: en.wikipedia.org/wiki/Design_by_contract
@Adam I agree, contract is a better word.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.