覆盖java中的构造函数

Res*_*had 2 java swing constructor

你好,我有一个用Java绘制明星的课程,它有点像魅力.在此之后我扩展了Star类以创建另一个具有扩展可能性的星(在这种情况下颜色必须不同)

由于某些原因,当我调用类并使用构造函数给出参数时,我的面板中只有子类颜色似乎有效.

这是我的代码

    public class Star {

    protected int radius;
    protected int xmiddelpunt;
    protected int ymiddelpunt;
    protected static Color color;

    public Star(int radius, int x, int y, Color color) {
        xmiddelpunt = x;
        ymiddelpunt = y;
        this.radius = radius;

        this.color = color;
    }

}
Run Code Online (Sandbox Code Playgroud)

和扩展的类

    public class StarRed extends Star {

    protected int x, y;
    protected static Color color;

    Random red = new Random();

    public StarRed(int radius, int x, int y, Color color) {
        super(radius, x, y, color);

        this.radius = radius;
        this.x = x;
        this.y = y;
        this.color = color;
    }
}
Run Code Online (Sandbox Code Playgroud)

我的面板类的构造函数如下:

    ArrayList<Star> stars = new ArrayList<Star>();
ArrayList<StarRed> rs = new ArrayList<StarRed>();

public HeavenPanel() {

    setBackground(Color.blue); // geef het paneel een blauwe kleur


    this.addMouseWheelListener(this); // set de mouselistener


    for(int i = 0; i < 10; i++) {
        stars.add(new Star (r.nextInt(30 + 50), r.nextInt(10 + 701), r.nextInt(10 + 701), Color.yellow));
    }

    for(int k = 0; k < 10; k++) {
        rs.add(new StarRed(40, r.nextInt(30 + 50), r.nextInt(30 + 50), Color.red));
    }

}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 6

第一个问题:

protected static Color color;
Run Code Online (Sandbox Code Playgroud)

这意味着该字段(您有两个......)在整个类型中共享.我原以为这是一个实例字段,因此不同的颜色可以是不同的颜色.相反,所有的星星都是相同的颜色,除非你有一些StarRed使用该color字段的代码,在这种情况下你可能有两种颜色的星......但它仍然是不对的.

问题二:你的StarRed类定义它自己的字段x,y以及color,尽管他们也正在超类中声明.然后,您将设置超类的radius字段的值,尽管已经在超类构造函数中设置了该值.

基本上它现在有点困惑.您应该计算出与类型相关联的信息而不是任何特定实例(在这种情况下应该是静态字段)以及与各个实例相关联的信息(在这种情况下,这些实例应该是实例字段).你几乎应该在子类和超类中使用相同的字段名称 - 而且我个人建议将所有字段设为私有(除了常量之外).

最后,为什么StarRed构造函数想要取一个Color呢?它不应该永远是红色的吗?


cjd*_*jds 5

您正在覆盖静态变量颜色.

静态关键字表示该类的所有实例都具有相同的颜色.

所以父和子指的是同一个静态变量.

因此,因为您在以后设置子颜色只有子颜色工作.

更改您的代码并删除静态