1

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!

1
  • Depends what the method does. Commented Dec 11, 2015 at 14:33

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! Are there other differences?
Generics start getting interesting on class-level. On Method-level using polymorphism is often equal.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.