public class B extends C <A> {
}
What does this mean? That C needs to extend A? What extra restriction am I putting instead of just saying B extends C?
Non-generic class can't extend generic class except of those generic classes which have already pre defined types as their type parameters.
Yes you can do it.
We can add generic type parameters to class methods, static methods, and interfaces. Generic classes can be extended to create subclasses of them, which are also generic. Likewise, interfaces can also be extended.
Yes, you can define a generic method in a non-generic class in Java.
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
.
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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With