我正在尝试理解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();
}
}我不明白/理解为什么我应该使用/实现area1而不是area2 (反之亦然)。我是不是遗漏了什么?这两种方法不是做同样的事情吗?
它让我对Java中的泛型感到有点困惑
发布于 2013-05-21 03:08:35
没有充分的理由创建area1方法。area2方法更可取。当存在与特定但未知类型的关系时,使用泛型。在这里,参数shape没有什么特别的地方。接口Shape已经允许我们使用area方法,所以我们不关心Shape的哪个具体实现作为shape传入。所以这里不需要泛型。
使用
public long area2(Shape shape)https://stackoverflow.com/questions/16656517
复制相似问题