public class B extends C {
}
What does this mean? That C needs to extend A? What extra restriction am I putting instead of just saying B ext
Class B
is a C
.
C
and B
are parameterized with an A
. (Which means they can have methods and such that use A
methods, or the methods of classes that descend from A.)
A classic use case for this would be that you have a DAO (Data Access Object). You make a generic DAO with some basic methods, like GenericDAO
with a generic save
method. To make it so other DAOs can extend GenericDAO
, you parameterize that class with Entity
, and you make sure all your Entity
s are saveable.
Then you have GenericDAO<Entity
, and a bunch of implementations of that, for example UserDAO extends GenericDAO<User>
where User is an entity.
public class B extends C <A> {
}
C<A>
does not mean that C
is extending A
, it means it can have A
as the type parameter.
This is very similar to Comparable<T>
and Comparator<T>
interfaces in java.
Consider following example
public class NameSort implements Comparator<Employee> {
public int compare(Employee one, Employee another){
return (int)(one.getName() - another.getName());
}
}
means that Comparator is using Employee objects for sorting them using its name.
You can also take another example
List<String> list = new ArrayList<String>();
This line means that List
is using String
objects as parameters
In this case, C
is a class that can take a generic parameter, and you are giving it a specific type A
as the parameter. Then, B
extends that specific parameterization of C
.
For example, suppose:
class C<T> {
T example();
}
class B extends C<Integer> {
}
Then B.example()
would return an Integer
.
That doesn't mean anything, unless there are some methods defined in Class C
or its ascendants, to either accept or return Type A parameters.
By doing so you are ensuring the Type safety by imposing restrictions saying "They can accept or return objects of Type A".
You are defining a class B that inherits from class C, parameterized with type A. A must be a class or interface.
E.g.
class MyStringList extends ArrayList<String>
means that MyString
IS AN ArrayList
that will only contain String
elements. This class could then define e.g. a concatenate()
method that returns the concatenation of all Strings
in the list.
Because of this inheritance, you will be able to assign an instance to a List<String>
variable:
List<String> strings = new MyStringList();
But you will not be able to assign it to List
type variables with other parameters:
List<Object> objects = new MyStringList(); // does not compile