如果您只是在寻找针对已定义子类的方法链,那么以下方法应该有效:
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



