Reputation: 10048
I'm new to Java and is trying to learn the concept of initialisation. I saw this statement online:
List<Integer> numList = Arrays.asList(1,2,3,4,5,6);
I understand interface type can't be instantiated. But Arrays.asList()
method returns a object that implement List<>
interface. Does this statement count as initialisation? Have I created an instance of class that implement List<>
interface?
Upvotes: 1
Views: 36
Reputation: 1183
A reference variable can be declared as a class type or an interface type.
If the variable is declared as an interface type, it can reference any object of any class that implements the interface.
So you have created an object which is being referenced by the interface variable.
Upvotes: 1
Reputation: 7042
Does this statement count as initialization?
Yest it does. Because you initialize the reference variable numList
.
Have I created an instance of class that implement List<> interface?
No, You didn't created an instance of class that implement List<> interface.But The Arrays.asList()
method created an instance of class ArrayList
returned the reference of that object to you.
If you read the source code you will find something like:
public static <T> List<T> asList(T... a) {
return new ArrayList<>(a);
}
Now new ArrayList<>(a);
this statement creating an instance.
And yes ArrayList
implement List
interface.
Upvotes: 0
Reputation: 8575
Yes, the statement counts as initialization; you initialized the numList
variable by assigning it a value: the value returned by Arrays.asList()
.
When Arrays.asList(arr)
is called, it instantiates an ArrayList
based on the input array arr
. An ArrayList
is a specific implementation of the abstract class AbstractList
, which itself implements the List
. So, while ArrayList
does not directly implement the List
interface, it can be treated like one through polymorphism.
For more details, refer to The Java Tutorial on Creating Objects and Java Tutorials on Interfaces, especially the section on using an interface as a type. You may also benefit by reading the tutorials about Inheritance and Initializing Fields.
Upvotes: 2