java - 为什么使用 <T extends Superclass> 而不仅仅是 Superclass?

标签 java generics

早上好,这是从 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/

相关文章:

delphi - 使用泛型时如何处理 Delphi Simple 类型?

java - 让我的椭圆成为一个按钮以在同一窗口上显示一些数据?

java - 如何从另一个类 (SendMail) 运行 main(String [] args)

java - 有没有办法从 Intellij 的调试器中过滤嘈杂的堆栈帧?

java - 我们可以确保 @beforesuite 在 dataprovider 之前被调用吗?

java - com.mysql.jdbc.PacketTooBigException java

java - 类类型的可变参数 - Java

c# - "Double"不是 't get cast as "IComparable<Double>"

c# - 实现接口(interface)还是 double 的泛型?

c# - 如何在不知道类型的情况下转换泛型类型