I have classes in advanced programming at my university and I have a little trouble understanding how this code works.
public final class GenericClass<T> {
private void overloadedMethod(Collection<?> o) {
System.out.println("Collection<?>");
}
private void overloadedMethod(List<Number> o) {
System.out.println("List<Number>");
}
private void overloadedMethod(ArrayList<Integer> o) {
System.out.println("ArrayList<Integer>");
}
public void method(List<T> l) {
overloadedMethod(l);
}
public static void main(String[] args) {
GenericClass<Integer> test = new GenericClass<Integer>();
test.method(new ArrayList<Integer>());
}
}
Why does this code print "Collection<?>"?
There are two types of polymorphism in Java: compile time polymorphism and run time polymorphism in java. This java polymorphism is also referred to as static polymorphisms and dynamic polymorphisms.
To solve this, polymorphism in Java allows us to create a single method render() that will behave differently for different shapes. Note: The print() method is also an example of polymorphism. It is used to print values of different types like char , int , string , etc.
Dynamic polymorphism is a process or mechanism in which a call to an overridden method is to resolve at runtime rather than compile-time. It is also known as runtime polymorphism or dynamic method dispatch. We can achieve dynamic polymorphism by using the method overriding.
In Object-Oriented programming languages there are three types of polymorphism: subtype polymorphism, parametric polymorphism, and ad-hoc polymorphism.
The declaration of method(List<T> l)
does not specify any bounds on the type T. There is no guarantee that T is Number or a subclass of Number. Therefore, the compiler can only decide that this method calls overloadedMethod(Collection<?> o)
.
Remember: after compilation, the information about generics is not available anymore in the class files.
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