【问题标题】:How do I ensure the type of a generic method in my implementation?如何在我的实现中确保泛型方法的类型?
【发布时间】:2017-11-07 11:24:56
【问题描述】:

这是我第一次在这里提问,所以我希望我能正确发布所有内容。

我正在处理我的任务,但我有点卡在这个问题上。有四类形状(圆形、圆锥、球体和矩形)都实现了接口 GeometricShape....

public interface GeometricShape {
    public void describe();  
}

问题是向接口添加一个名为 supersize() 的新方法,该方法将采用当前形状并返回一个相同类型的形状,该形状使用泛型的大小加倍。提示说要将界面概括为这样的开始......

public interface GeometricShape<T extends GeometricShape<T>> {
    public void describe();
    public T supersize();
}

所以 T 只能是几何形状。但是当这样做时, Rectangle.supersize() 有可能返回一个圆。我怎样才能通过仅修改接口代码来避免这种情况发生(例如 Rectangle.supersize() 只能返回 Rectangle)?

【问题讨论】:

    标签: java generics interface


    【解决方案1】:

    诀窍不在于接口定义,而在于类声明。

    对于矩形,定义如下:

    public class Rectangle implements GeometricShape<Rectangle> {
       public void describe() {// do stuff}
       public Rectangle supersize() {
          return new Rectangle()
          //this should fail since you have specified T
          //return new Circle()
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多