parent 和 child 类 之间的设计建议?

An advice for a design between parent and child classes?

我正在研究物理模拟。

我有一个 ArrayList 可以容纳我模拟中的所有 objects。我有一个 parent class: Shape 和两个 child classes: CircleRectangle.

parent class 当然没有 draw() 方法,但是每个 child class 都有。因此,当我循环遍历列表以绘制每个元素时,它不允许我这样做,因为 Shape class 中没有 draw() 方法(因为我将列表定义为 ArrayList<Shape>,并使用 child class 实例添加每个新元素)。

有什么办法可以很好地解决这个问题吗?

它似乎为 Shape class 提供了一个抽象方法,其中所有子class 都有一个共同的行为,最适合手头的任务。

认为这是 Shape class:

public abstract class Shapes{
    public abstract void Draw();
}

Rectangle class:

public class Rectangle extends Shapes{
    public void Draw(){
        System.out.println("Rectangle");
    }
}

Circle class:

public class Circle extends Shapes{
    public void Draw(){
        System.out.println("Circle");
    }
}

现在考虑到 CircleRectangle 都是 Shape 类型,您可以创建 Circle or/and Rectangle 类型的对象,将它们添加到 ArrayList,对其进行迭代,然后在每个对象上调用 Draw() 方法,如下所示:

ArrayList<Shapes> shapes = new ArrayList<>();
shapes.add(new Circle());
shapes.add(new Rectangle());
shapes.forEach(Shapes::Draw);

在每个对象上调用 Draw() 方法时的结果:

Circle
Rectangle

我就是这样做的。

一个名为 Shapes 的 class 具有 List<Shape> 的字段 Shape 是一个包含方法 draw() getArea() 或任何其他方法的接口。 有尽可能多的 classes 实现 Shape、圆形、矩形、正方形等

前进的最巧妙方法是使用接口。

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 与其子级共享一些其他逻辑,您可以创建一个 AbstractShape class 使用任何附加代码实现 Shape 并使用此抽象 class 扩展子级 classes ].