简体   繁体   中英

Java difference between two methods (generics)

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!

PS: 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!

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 eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM