我想你想要做的是以下幾點:
public abstract class Draw<T extends Draw> {
public abstract T duplicate();
}
public class Circle extends Draw<Circle> {
@Override
public Circle duplicate() {
return new Circle();
}
}
public class Square extends Draw<Square> {
@Override
public Square duplicate() {
return new Square();
}
}
- 上
T
使用仿製藥的(有限制,應延長Draw
,以避免奇怪的遺傳,如Circle extends Draw<List>
)
- 添加
abstract
關鍵字在Draw
類
然後,您可以執行以下操作:
Square originalSquare = new Square();
Circle originalCircle = new Circle();
Square duplicatedSquare = originalSquare.duplicate();
Circle duplicatedCircle = originalCircle.duplicate();
編輯
沒有仿製藥,你可以做這樣的事情:
public abstract class Draw {
public abstract Draw duplicate();
}
public class Circle extends Draw {
@Override
public Circle duplicate() {
return new Circle();
}
}
public class Square extends Draw {
@Override
public Square duplicate() {
return new Square();
}
}
感謝Pavel,rgettman和Enno Shioji,我不知道「協變返回類型」。
繪製應該是一個抽象類。否則它看起來很好 – k2col