[英]Understanding java generic methods
我正在尝试理解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中的泛型有点困惑
在您的示例中,由于T
type参数未在任何返回值中使用,因此没有区别。
但是,假设您有以下方法:
public <T extends Shape> T movedShape1(T shape) {
return shape.move();
}
public Shape movedShape2(Shape shape) {
return shape.move();
}
在这里你可以看到使用movedShape1()
的明显优势。 您可以获得更具体的返回值类型,而不会丢失任何类型的安全性。
创建area1
方法没有充分的理由。 area2
方法是优选的。 当与特定但未知类型存在关系时,将使用泛型。 这里,参数shape
没有具体说明。 接口Shape
已经允许我们使用area
方法,因此我们不关心Shape
哪个特定实现作为shape
传递。 因此这里不需要泛型。
使用
public long area2(Shape shape)
我是这种情况 - 形状不是一个(抽象)类而是一个接口,所以它必须实现(以通用形式思考扩展) - 我会说它们确实相同,并且添加泛型只会影响到什么是真的继续
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.