Java中的OOP:使用方法链接的类inheritance

我有一个父类,它定义了一个chainer方法的集合(返回“this”的方法)。 我想定义多个子类,这些子类包含自己的chainer方法,但也“覆盖”父方法,以便返回子类的实例而不是父类。

我不想在每个子类中重复相同的方法,这就是为什么我有一个包含所有子类共享的方法的父类。 谢谢。

class Chain { public Chain foo(String s){ ... return this; } } class ChainChild extends Chain { //I don't want to add a "foo" method to each child class /* public ChildChain foo(String s){ ... return this; } */ public ChainChild bar(boolean b){ ... return this; } } ChainChild child = new ChainChild(); child.foo().bar(); //compile error: foo() returns a "Chain" object which does not define the bar() method. 

父类中返回this方法的方法仍将返回对子类对象的引用。 您将只能将其视为父类的对象(除非您将其强制转换),但实际上它将是其原始类型。

你可以考虑使用这样的generics:

 // This seems a bit too contrived for my liking. Perhaps someone else will have a better idea. public class Parent> { T foo () { return (T) this; } } public class Child extends Parent { public void bar () { Child c = foo(); } } 

我根据您的需要使用generics编写了这个示例。

 class Parent { public  T foo() { return (T)this; } } class Child extends Parent { } class AnotherChild extends Parent { } public class Test { public static void main(String[] args) { Parent p = new Child(); System.out.println(p); Child c = p.foo(); System.out.println(c); //throws ClassCastException here since Child is not AnotherChild AnotherChild ac = p.foo(); System.out.println(ac); } } 

以下是OldCurmudgeon方法的改进:

 public class Parent> { @SuppressWarnings("unchecked") private final This THIS = (This)this; public This foo() { //... return THIS; } public This bar() { //... return THIS; } } public class Child extends Parent { // you can override super with covariant return type @Override public Child bar() { super.bar(); return this; } } Child child = new Child() .foo() .bar(); 

改进是仅对未经检查的强制转换进行一次,并将其保存为常量THIS,您可以将其重复用作方法链的返回值。

这将删除每个方法中未经检查的强制转换,并使代码更清晰。

您可以通过返回Child而不是This(协变返回类型)来覆盖Parent的方法。

你可以施展它。

 ChainChild child = new ChainChild(); ((ChainChild) child.foo()).bar(); 

你可以尝试:

 public ? extends Chain foo() { return this; } 

但即使它汇编,我也不确定这会有所帮助。