gpt4 book ai didi

两种方法(泛型)之间的Java区别

转载 作者:行者123 更新时间:2023-11-29 03:02:02 25 4
gpt4 key购买 nike

考虑类层次结构

public class A {
public void say() {
System.out.println("I am A");
}
}

public class B extends A {
public void say() {
System.out.println("I am B");
}
}

在第三堂课中我有两种不同的方法

private static void print(A input) {
}

private static <T extends A> void print2(T input) {
}

它们之间的“区别”是什么?

我可以用 A 的实例和 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);
}
}

感谢您的帮助!

P.S.:两者的区别

private static void print(java.util.List<A> input) {
}
private static <T extends A> void print2(java.util.List<T> input) {
}

很清楚!

最佳答案

从实际原因来看,两者并没有太大区别。您可以通过

调用第二种方法
<B>test2(new B());

然后当您尝试将 is 与 A 一起使用时它会失败

<B>test2(new A()); //Compile error

虽然这对它没有多大用处。

但是:当您例如添加返回类型。

public void <T extends A> T test2(T var) {
//do something
return var;
}

你可以调用:

B b = new B();
B b2 = test2(b);

在不使用泛型的情况下调用类似的方法将需要强制转换。

关于两种方法(泛型)之间的Java区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34225819/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com