我正在研究物理模拟。
我有一个 ArrayList
它包含我模拟中的所有对象。我有一个父类:Shape
和两个子类:Circle
和 Rectangle
.
父类当然没有draw()
方法,但每个子类都有。因此,当我循环遍历列表以绘制每个元素时,它不允许我这样做,因为没有 draw()
。 Shape
中的方法类(因为我将列表定义为 ArrayList<Shape>
,并为每个新元素添加一个子类实例)。
有没有一种好的、简洁的方法来解决这个问题?
最佳答案
前进的最简洁的方法是使用接口(interface)。
public interface Shape {
void draw();
}
public class Rectangle implements Shape {
@Override
public void draw() { // draw rect }
}
public class Circle implements Shape {
@Override
public void draw() { // draw circle }
}
如果您希望 Shape 与其子类共享一些其他逻辑,您可以创建一个使用任何附加代码实现 Shape 的 AbstractShape 类,并使用此抽象类扩展子类。
关于java - 父子类之间的设计建议?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43433127/