Reputation: 4647
Consider the class hierarchy
public class A {
public void say() {
System.out.println("I am A");
}
}
and
public class B extends A {
public void say() {
System.out.println("I am B");
}
}
In a third class I have two different methods
private static void print(A input) {
}
private static <T extends A> void print2(T input) {
}
What is the "difference" between them?
I can both call them with an instance of A
and all subclasses of A
:
public class Test {
private static void print(A input) {
input.say();
}
private static <T extends A> void print2(T input) {
}
public static void main(String[] args) {
B b = new B();
print(b);
print2(b);
}
}
Thank you for your help!
P.S.: The difference between
private static void print(java.util.List<A> input) {
}
private static <T extends A> void print2(java.util.List<T> input) {
}
is clear!
Upvotes: 1
Views: 117
Reputation: 3164
Well from a practical reason there is not so much difference there. You could call the second method by
<B>test2(new B());
It would fail then when you try to use is with an A
<B>test2(new A()); //Compile error
Although this does not make a big use for it.
However: The generic declaration does make sence when you e.g. add the return-types.
public void <T extends A> T test2(T var) {
//do something
return var;
}
that you could call with:
B b = new B();
B b2 = test2(b);
while calling a similar method without generics would require a cast.
Upvotes: 4