Generics
What you see here are generics. It has nothing to do with polymorphism.
Generics are something like an argument is for a method:
public static void foo(int bar) { ... }
The method foo
wants a user to give it some int
value when it is called. The method itself refers to that value by the local variable bar
. A call might look like
foo(5);
foo(8);
If you have a generic class like
public class Pair<A, B> { ... }
the class Pair
wants the user to declare two types when using it. The class refers to them by the placeholders A
and B
. So one might use it like:
Pair<String, Integer> stringAndInteger;
Pair<Dog, Car> dogAndCar;
The nice thing about it is that the compiler can use this information to ensure that dogAndCar
can really only be used with Dog
and Car
for A
and B
. So if the class has a method like
public void setFirst(A first) { ... }
you can not call the method with the wrong type, like dogAndCar.setFirst(10);
. The compiler knows A
is Dog
for dogAndCar
and will not allow that you use it with anything that is not Dog
.
For more on the topic, read the official tutorial for generics.
Polymorphism
Polymorphism refers to the concept of one class implementing features of a parent class but overriding some other or adding new functionality.
Let's consider the following parent class
public class Animal {
public void makeNoise() {
System.out.println("Hello");
}
}
Now we extend that class and override the method. Additionally we add a second method:
public class Dog extends Animal {
@Override
public void makeNoise() {
System.out.println("wuff wuff");
}
public String getName() {
return "John";
}
}
If we use the makeNoise
method on a Dog
, we will see "wuff wuff"
and not "Hello"
.
For more on this take a look at the official tutorial on polymorphism.
Note that you can further distinguish this into inheritance and polymorphism. Read What is the main difference between Inheritance and Polymorphism? for more.