java - 父子类之间的设计建议?

标签 java class parent-child simulation

我正在研究物理模拟。

我有一个 ArrayList它包含我模拟中的所有对象。我有一个父类:Shape和两个子类:CircleRectangle .

父类当然没有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/

相关文章:

html - 使子 div 适合其父级宽度的跨浏览器方法

jQuery父子元素点击事件

java - TilesViewResolver 在部署为 war 时不工作

java - 使用 Wildfly 11 复制 infinispan 缓存

java - 在 spring boot 2.0.5 中将具有不同数据类型的图像从 Angular 7 发送到 Rest API

c++ - 为什么我不能这样做(错误 C2275 : 'A' : illegal use of this type as an expression)

C++ 访问类内容器的 begin()/end() 方法

java - 异常org.hibernate.exception.GenericJDBCException : could not extract ResultSet while feching data using hql

c++ - C2679 : binary '<<' : no operator found which takes a right-hand operand of type 'student' (or there is no acceptable conversion)

c++ - 在不丢失数据的情况下将子类对象存储在同一个容器中?