[英]How to create an Interface for a class that extends JDialog (or in general another class)
[英]Create general method to fit interface and general parent class
我有以下方法:
private void setFilledAndAdd(Shape obj, Color col, int x, int y) {
obj.setFilled(true); // needs interface Fillable
obj.setFillColor(col);
add(obj, x, y); // needs children of Shape (or Shape itself)
}
如果我添加其中一行:
setFilledAndAdd(oval, color, x, y);
编译时间错误apears in line obj.setFilled(true);
和行obj.setFillColor(col);
。 因为Shape
不可Fillable
。 未定义Shape类型。
在方法变更参数类型setFilledAndAdd
为Fillable
(未Shape
)导致编译线时错误add(obj, x, y);
。 在这种情况下它需要Shape
。
我使用的Shape
所有孩子都是Fillable
。 给我一个提示,如何使这个方法工作。
谢谢。
如果您可以控制Shape
和Fillable
源,我只需重写,以便所有形状都可填充,如果可能的话。 你也可以有一个public abstract class FillableShape extends Shape implements Fillable
而不是继续使用类型系统。
否则,您可以使用类型转换,并通过运行时检查来确保形状是可填充的:
if(obj instanceof Fillable){
((Fillable) obj).setFilled(true);
((Fillable) obj).setFillColor(col);
add(obj, x, y);
} else {
// show an error message or something
// (or just draw the shape without filling it, if you want)
}
您可以使用泛型来表示您期望具有这两个特征的对象
private <T extends Shape & Fillable> void setFilledAndAdd(T obj, Color color, int x, int y){
obj.setFilled(true); // needs interface Fillable
obj.setFillColor(color);
add(obj, x, y);
}
private void add(Shape s, int x, int y){
// whatever code you have goes here.
}
这对我来说很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.