我有一個父類,它定義了一個chainer方法(返回「this」的方法)的集合。我想要定義多個包含自己的chainer方法的子類,但也要「覆蓋」父方法,以便返回子類的實例而不是父類。Java中的OOP:使用方法鏈接進行類繼承
我不想在每個子類中重複相同的方法,這就是爲什麼我有一個包含所有子類共享方法的父類。謝謝。
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.
可能重複的[我可以有一個抽象的生成器類在Java與方法鏈接,而不做不安全的操作?](http://stackoverflow.com/questions/5818504/can-i-have-an-abstract-builder- java-with-method-chaining-without-doing) – artbristol 2013-02-24 17:19:20
我很好奇,在什麼情況下使用這樣的('child.foo().bar();')調用? – vijay 2013-02-24 17:23:09
@vijay有一些設置,所有的子類都可以使用。例如,一個方法需要一個布爾參數來啓用/禁用某個設置。 – Michael 2013-02-24 17:30:03