class 未继承自扩展到 JComponent 的 class

class not inheriting from class that extends to JComponent

我有这些 classes;

public class Car extends JComponent {

}

public class Mazda extends Car {

}

public class Subaru extends Car {
}

在我的车里class我覆盖了绘制组件的方法

    @Override
public void paintComponent(Graphics g) {
    //why my planets aren't painted by this method
    if (this instanceof Mazda) {
        g.fillOval(0, 0, this.getWidth(), this.getHeight());
        System.out.println(this.getClass());
    }
    if (this instanceof Subaru) {
        g.setColor(Color.blue);
        g.fillOval(0, 0, this.getWidth(), this.getHeight());
        System.out.println(this.getClass());
    }
}

它很好地绘制了 mazda 的实例,但是 subaru 的实例的代码永远不会被调用。 subaru好像没有继承Car的Jcomponent吧?或者为什么不调用 painComponent? Java 的新手,所以我可能遗漏了一些基本的东西

斯巴鲁 class 肯定是从 Car 继承的,但可能根本没有显示。有一些原因,但没有看到它只是猜测的代码:

  1. Subaru 未添加到父级,或被另一个实例(马自达?)取代
  2. 添加的父级未显示
  3. 斯巴鲁离屏,不用画了
  4. 斯巴鲁零次元,无漆可画
  5. ...

注意:使用 instanceof 通常表示 OOP 设计存在缺陷: Why not use instanceof operator in OOP design?

如果每个 subclass 都有自己的 paintComponent 版本,而根本不必使用 instanceof,那就更 OO 了。这样做的一个好处是:如果添加新车型,汽车 class 不需要更改。

我认为,你的设计有问题,因为,如果你想从 super class 中使用 @Override 方法,好的选择是在基础 class 中进行,比如 MazdaSubaru, 特别是,您想指定不同的行为。在像 Car 这样的抽象 class 中,您可以 @Override 方法,该方法对于 MazdaSubaru 是常见的,并且对于超级 child 并不重要 class 这样做吧。所以,我想你可以这样写这个结构:

class  Car extends JComponent{

}

class Mazda  extends Car{

  @Override
  public void paintComponents(Graphics g) {
    g.fillOval(0, 0, this.getWidth(), this.getHeight());
    System.out.println(this.getClass());
  }
}


class Subaru extends Car{

  @Override
  public void paintComponents(Graphics g) {
    g.setColor(Color.blue);
    g.fillOval(0, 0, this.getWidth(), this.getHeight());
    System.out.println(this.getClass());
  }

}

然后创建 class 马自达 Mazda mazda = new Mazda() 并调用方法:mazda.paintComponent(... 或使用多态性并创建 e.q。 Mazda 像这样:Car mazda = new Mazda();