[英]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
: 我可以两者都具有一个实例称他们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);
}
}
Thank you for your help! 谢谢您的帮助!
PS: The difference between PS:两者之间的区别
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 然后,当您尝试使用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. 而调用没有泛型的类似方法则需要强制转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.