【问题标题】:How to use abstract class' child type as the type of an abstract method's parameter?如何使用抽象类的子类型作为抽象方法的参数类型?
【发布时间】:2016-10-16 15:49:36
【问题描述】:

假设有 2 个类:

  • Foo(一个抽象类)
  • Bar(Foo 的孩子)

我希望Foo的抽象函数的参数类型与实现Foo的子类的类型相匹配(这样的类可以是Bar)。

我以为我可以使用受约束的泛型类型,但我不知道如何约束类型以匹配子类。

例子:

abstract class Foo {
    public abstract boolean testSth( [Type of the child] obj );
}

class Bar extends Foo {
    @Override
    public boolean testSth( Bar obj ) { // I need the parameter to be of type Bar
        // ...
    }
}

【问题讨论】:

  • 将泛型设置为任何扩展Foo
  • 为什么不简单地声明没有泛型类型的方法并像testSmth(Foo obj) 一样使用Foo?可以肯定的是,您将无法传递抽象 Foo 类的实例,因为我们无法创建此类的实例。我们只能创建非抽象类的实例,因此您可以确定它将是 Bar 的实例或在某个点扩展的其他非抽象类 Foo
  • @Pshemo:关键是Bar.testSth 只能处理Bar,而不是Baz 或其他派生类型。这种情况并不少见。
  • @Pshemo:虽然这不是问题的最简单解决方案 - OP 希望将对 Foo.Bar 的调用限制为传入 Bar 作为参数的调用。您的评论并未提出解决方案。项目符号列表之后的声明非常清楚 OP 的目标是什么,IMO。
  • @JonSkeet 重读问题后,我明白你的意思。我太专注于标题,错过了最重要的事实,即 OP 希望确保子类中的方法也只接受 that 子对象。感谢您的 cmets。

标签: java types abstract-class


【解决方案1】:

显然,您可以将子类型作为泛型类型传递给父类:

abstract class Foo<T> {
   // or Foo<T extends Foo<T>>
   public abstract boolean testSth(T obj );
}

class Bar extends Foo<Bar> {
    @Override
     public boolean testSth( Bar obj ) { // I need the parameter to be of type Bar
       // ...
    }
 }

【讨论】:

  • 你可能想要T extends Foo&lt;T&gt;
  • 我实际上已经尝试避免这种使用类类型冗余定义的方法,但我猜Java没有提供任何构造来引用方法参数中的子类型,所以这个解决方案是(不幸的是)唯一可用的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-06-26
  • 1970-01-01
  • 2014-12-01
  • 1970-01-01
  • 2016-02-01
  • 2023-03-29
  • 1970-01-01
相关资源
最近更新 更多