[英]How do I ensure the type of a generic method in my implementation?
這是我第一次在這里提問,希望我能正確張貼所有內容。
我正在做作業,但在這個問題上有些卡住。 共有四類形狀(圓形,圓錐形,球形和矩形),它們均實現了GeometricShape接口。
public interface GeometricShape {
public void describe();
}
問題是在接口中添加一個名為supersize()的新方法,該方法將采用當前形狀,並返回使用泛型將相同類型的形狀放大一倍的形狀。 提示說將接口概括為這樣的起點...
public interface GeometricShape<T extends GeometricShape<T>> {
public void describe();
public T supersize();
}
這樣T只能是幾何形狀。 但是,當這樣做時,Rectangle.supersize()可能返回一個圓。 如何通過僅修改接口代碼來做到這一點(例如Rectangle.supersize()只能返回Rectangle)?
訣竅不在接口定義中,而在類聲明中。
對於矩形,將其定義為:
public class Rectangle implements GeometricShape<Rectangle> {
public void describe() {// do stuff}
public Rectangle supersize() {
return new Rectangle()
//this should fail since you have specified T
//return new Circle()
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.