早上好,这是从 oracle 教程中摘录的, 假设我们有
class Shape { /* ... */ }
class Circle extends Shape { /* ... */ }
class Rectangle extends Shape { /* ... */ }
方法
public static <T extends Shape> void draw(T shape) { /* ... */ }
我的问题如下,你为什么要使用 <T extends Shape>
而不是 Shape
? 难道他们返回的不是完全相同的东西吗?在这种情况下是一个形状。
最佳答案
对于不返回任何内容的 draw
方法,也许您是正确的,但假设您有一个具有返回值的通用方法:
public static <T extends Shape> T draw(T shape) { /* ... */ }
现在,使用类型绑定(bind),您可以编写:
Rectangle r = ...
Rectangle r2 = draw(r);
Circle c = ...
Circle c2 = draw(c);
另一方面,如果您将签名更改为
public static Shape draw(Shape shape) { /* ... */ }
你只能写:
Rectangle r = ...
Shape r2 = draw(r);
Circle c = ...
Shape c2 = draw(c);
或使用显式转换(甚至可能在运行时失败,因为现在 draw
可以返回 Shape
的任何子类型):
Rectangle r = ...
Rectangle r2 = (Rectangle) draw(r);
Circle c = ...
Circle c2 = (Circle) draw(c);
关于java - 为什么使用 <T extends Superclass> 而不仅仅是 Superclass?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45128061/