如果您只是针对定义的子类寻找方法链接,那么以下内容应该起作用:
public class Parent {
public T example() {
System.out.println(this.getClass().getCanonicalName());
return (T)this;
}
}
如果你喜欢它可以是抽象的,那么一些指定通用返回类型的子对象(这意味着你不能从ChildA访问childBMethod):
public class ChildA extends Parent {
public ChildA childAMethod() {
System.out.println(this.getClass().getCanonicalName());
return this;
}
}
public class ChildB extends Parent {
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