的問題是,我創造的任何LeftCell/RightCell對象,請 當然無法獲得這場平局()方法。
特定於子類的方法當然不能在不知道它的父實例上調用。
由於您的要求是
繼承層次改變,以減少代碼的重複 在一個項目中,我有兩個類LeftCell和RightCell,既 擴展類細胞。 現在,爲了避免代碼重複,我想在 多個其他項目
我認爲你應該做的事情有點不同使用這些對象。
如果你想避免爆炸的組合可能的班,而不是複製LeftCell
和RightCell
就像你的例子數量:
Cell
CellProjectX
LeftCell
RightCell
可能由最終完成:
Cell
CellProjectY
LeftCell
RightCell
Cell
CellProjectZ
LeftCell
RightCell
你應該贊成繼承的構成來創建你的特定項目實現。
對於常見的細胞結構:
的Cell
子類可以是一個Cell
接口定義任何Cell
常用的方法,你可以有一個AbstractCell
類,定義了它常見的實現。
public interface Cell{
int getValue();
void setValue(int value);
}
public abstract class AbstractCell implements Cell{
...
}
然後,你可以通過擴展AbstractCell
定義RightCell
和LeftCell
:
public class RightCell extends AbstractCell {
...
}
public class LeftCell extends AbstractCell {
...
}
有關具體到一個項目的小區實現:
現在,在一個特定的項目,你可以一個創建通過將其與Cell
實例(最後是LeftCell
或)組合來實現自定義Cell
實現實例),它將在特定項目具體類中用於實現接口Cell
。
在具體實施中,您當然可以添加任何特定於該項目的方法。
例如:
class CellProject1 implements Cell {
private Cell cell;
CellProject1 (Cell cell){
this.cell = cell;
}
public int getValue(){
cell.getValue();
}
public void setValue(int value){
cell.setValue(value);
}
public void draw(){
...
}
}
可以使創建CellProject1
情況下,這樣的:
CellProject1 leftCell = new CellProject1(new LeftCell());
CellProject1 rightCell = new CellProject1(new RightCell());
leftCell.draw();
rightCell.draw();
而且在使用CellProject2
實例與特定write()
方法的另一個項目,你可以寫:
CellProject2 leftCell = new CellProject2(new LeftCell());
CellProject2 rightCell = new CellProject2(new RightCell());
leftCell.write();
rightCell.write();