我正在尝试理解Java中的泛型方法.给出以下代码:
public class GenericTest {
interface Shape {
public long area();
}
public static class Triangle implements Shape
{
private long base, height;
public long area() { return (base * height) / 2; }
}
public static class Rectangle implements Shape
{
private long width, height;
public long area() { return width * height; }
}
public <T extends Shape> long area1(T shape)
{
return shape.area();
}
public long area2(Shape shape)
{
return shape.area();
}
}
Run Code Online (Sandbox Code Playgroud)
我无法看到/理解为什么我应该使用/实现area1而不是area2(反之亦然).我错过了什么吗?这两种方法都不一样吗?
它让我对Java中的泛型有点困惑
Kep*_*pil 13
在您的示例中,由于Ttype参数未在任何返回值中使用,因此没有区别.
但是,假设您有以下方法:
public <T extends Shape> T movedShape1(T shape) {
return shape.move();
}
public Shape movedShape2(Shape shape) {
return shape.move();
}
Run Code Online (Sandbox Code Playgroud)
在这里你可以看到使用的明显优势movedShape1().您可以获得更具体的返回值类型,而不会丢失任何类型的安全性.
创建该方法没有充分的理由area1。该area2方法是优选的。当与特定但未知的类型存在关系时,将使用泛型。这里,参数 没有什么具体的内容shape。该接口Shape已经允许我们使用该area方法,因此我们不关心作为Shape传入的具体实现shape。所以这里不需要泛型。
使用
public long area2(Shape shape)
Run Code Online (Sandbox Code Playgroud)