Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advanced polymorphism in Java

Tags:

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<?>"?

like image 716
Tomasz Bielaszewski Avatar asked Mar 12 '13 12:03

Tomasz Bielaszewski


People also ask

What are the types of polymorphism in Java?

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.

What is polymorphism in Java with examples?

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.

What is dynamic polymorphism in Java?

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.

What are the three types of polymorphism?

In Object-Oriented programming languages there are three types of polymorphism: subtype polymorphism, parametric polymorphism, and ad-hoc polymorphism.


1 Answers

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.

like image 108
gogognome Avatar answered Mar 29 '23 13:03

gogognome