我正在使用 JavaFX Shape
子类,我遇到了一个我认为相当奇怪的问题。我的目标是扩展其中几个形状子类(即 Rectangle
、 Circle
),以便向这些对象添加我自己的属性。例如, Rectangle
的扩展名子类看起来像这样:
public class MyRectangle extends javafx.scene.shape.Rectangle
implements SpecialInterface {
private SpecialAttributes specialAttributes;
// ...
// Constructors, getters and setters here
// ...
}
哪里SpecialInterface
可用于指定与将添加到MyRectangle
的新属性相关的方法。和MyCircle
,在本例中:
public interface SpecialInterface {
public SpecialAttributes getSpecialAttributes();
public void setSpecialAttributes();
}
但是,当我尝试创建引用 Rectangle
的这些子类的服务类时和Circle
,似乎我不能一般这样做。本质上,当我需要利用Shape
中的属性和方法时,问题就出现了。子类和 SpecialInterface
接口(interface):
public class ManipulationService{
public ManipulationService(<Undefined> myExtendedShape) {
// object from JavaFX Node, inherited by JavaFX Shapes (Circle, Rectangle, etc)
myExtendedShape.onRotate(new EventHandler<>(){
// ...
});
// a method from MyRectangle or MyCircle
myExtendedShape.getSpecialAttributes();
}
// ...
}
这里的问题是我无法为我的扩展形状创建一个父类(super class)来替换 <Undefined>
多于。具体来说,如果我创建一个父类(super class),由于缺乏多重继承,我无法扩展我想要在子类中扩展的特定形状。如果我替换 <Undefined>
与 Shape
不过,我随后就失去了对 SpecialInterface
中方法的访问权限。 。
我确信这种多重继承问题以前已经解决过,但我找不到解决方案。我感谢任何有关如何处理这种情况的建议。
最佳答案
您可以像这样定义ManipulationService
:
class ManipulationService<T extends Shape & SpecialInterface> {
public ManipulationService(T myExtendedShape) {
// method from Shape
myExtendedShape.onRotate(/* ... */);
// method from SpecialInterface
myExtendedShape.getSpecialAttributes();
}
}
关于java - 绕过不良设计实践 : Java Multiple Inheritance,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26701005/