Reputation: 923
I am learning generics in java.At first we made a arraylist of Integer and we added a value in list.
import java.util.ArrayList;
import java.util.List;
public class GenericsRunner {
public static void main(String[] args) {
ArrayList<Integer> numbers=new ArrayList<>();
numbers.add(1);
}
static <X extends List> void duplicate(X list) {
list.addAll(list);
}
}
The Method duplicate can be only used by those objects which are extending List
. But, since List
is interface
public interface List<E> extends Collection<E>
And ArrayList
is implemeting List
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable,
java.io.Serializable
I got stuck at this point. Extends is used by those classes which inherits the property from super class.
But how Arraylist
is extending List
? Actually ArrayList
is implementing List
. How is this extends keyword working for this implements mechanism? I am getting confused that it is using extends
and implements
are same?
Upvotes: 0
Views: 72
Reputation: 106
The reason is <X extends T>
means just that X
is inherited from T
. There is no special syntax for interfaces like when you describe inheritance in class declaration.
ArrayList
implements interface List
which means that it is inherited from List
, thus it is suitable for generic type <X extends List>
.
In Java any class can extend only one class. By default it's Object
when you do not specify another parent class. And class and interface can implement any amount of interfaces.
Hope this helps.
Upvotes: 1