使Java父类方法返回子类对象的方法

蒂莫菲·戈什科夫(Timofey Gorshkov):

从子类对象调用该方法时,是否有任何优雅的方法可以使位于父类中的Java方法返回子类的对象?

我想在不使用其他接口和方法的情况下实现此功能,并在没有类强制转换,辅助参数等的情况下使用此功能。

更新:

抱歉,我不太清楚。

我想实现方法链,但是父类的方法存在问题:调用父类方法时,我无法访问子类方法... 我想我已经提出了我的想法的核心。

因此,方法应返回类的this对象this.getClass()

加里·罗(Gary Rowe):

如果您只是在寻找针对已定义子类的方法链,那么以下方法应该有效:

public class Parent<T> {

  public T example() {
    System.out.println(this.getClass().getCanonicalName());
    return (T)this;
  }
}

如果愿意,可以是抽象的,然后是一些指定通用返回类型的子对象(这意味着您不能从ChildA访问childBMethod):

public class ChildA extends Parent<ChildA> {

  public ChildA childAMethod() {
    System.out.println(this.getClass().getCanonicalName());
    return this;
  }
}

public class ChildB extends Parent<ChildB> {

  public ChildB childBMethod() {
    return this;
  }
}

然后像这样使用它

public class Main {

  public static void main(String[] args) {
    ChildA childA = new ChildA();
    ChildB childB = new ChildB();

    childA.example().childAMethod().example();
    childB.example().childBMethod().example();
  }
}

输出将是

org.example.inheritance.ChildA 
org.example.inheritance.ChildA 
org.example.inheritance.ChildA 
org.example.inheritance.ChildB 
org.example.inheritance.ChildB

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章