【问题标题】:Referencing subclass in Java method declaration [duplicate]在 Java 方法声明中引用子类 [重复]
【发布时间】:2020-07-27 16:53:18
【问题描述】:

我正试图弄清楚一些事情,但谷歌搜索很困难,因为我不确定需要哪些关键字。假设我有这样的课程:

class MyClass {
    int i = 0;

    public MyClass increment() {
        i++;
        return this;
    }
}

然后我有一个子类:

class MySubClass extends MyClass { }

然后我想执行以下操作:

MySubClass mySubClass2 = new MySubClass().increment();

问题是increment 返回的对象被识别为MyClass 的实例而不是MySubClass,所以这不起作用。有没有办法在 MyClass 中声明 increment 以便它总是返回子类的类型?

【问题讨论】:

  • 您可以覆盖子类中的increment 方法以返回MySubClass 的实例。
  • 对,但是有没有办法让这种情况自动发生,而不是每次都必须覆盖?
  • 如果你想从多个子类返回this,它总是属于它们的类型。您可以做的节省一些麻烦的方法是将基类和increment() 声明为抽象。
  • 这被称为“自我类型”。 Java 没有此功能,但可以使用泛型实现类似的功能。

标签: java generics inheritance types


【解决方案1】:

您可以使用自界泛型:

class MyClass<M extends MyClass<M>> {
    int i = 0;

    public M self() {
      // unchecked cast here, because there is no guarantee that M is the self-type.
      return (M) this;
    }

    public M increment() {
        i++;
        return self();
    }
}

然后,像这样扩展类:

class MySubClass extends MyClass<MySubClass> { }

虽然很丑。

Ideone demo

【讨论】:

    猜你喜欢
    • 2012-12-14
    • 1970-01-01
    • 2018-07-10
    • 2020-12-24
    • 2017-03-12
    • 1970-01-01
    • 2015-07-10
    • 2019-02-26
    • 2011-06-16
    相关资源
    最近更新 更多