Hello I have a class that draws a star in Java what works like a charm. After this I have extended the Star class to create another star with extendes possibilities ( in this case the color has to be different )
for some reason in my panel when I call the classes and give the parameters with the constructor only the child class color seems to work.
here is my code
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;
}
}
and the extended class
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;
}
}
the constructor of my panel class is as follows:
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));
}
}
First problem:
That means that field (which you’ve got two of…) is shared across the whole type. I would have expected this to be an instance field, so different stars can be different colours. Instead, all stars are the same colour, unless you’ve got some code in
StarRedwhich uses thecolorfield, in which case you may have two colours of stars… but it’s still not right.Second problem: your
StarRedclass declares its own fields forx,y, andcolor, despite them also being declared in the superclass. You’re then setting the value of the superclass’sradiusfield despite that already having been set in the superclass constructor.Basically it’s all a bit confused at the moment. You should work out what information is associated with the type rather than any specific instance (in which case that should be a static field) and what information is associated with individual instances (in which case those should be instance fields). You should almost never use the same field name in a subclass and a superclass – and personally I’d suggest making all fields private (except possibly for constants).
Finally, why would the
StarRedconstructor want to take aColorat all? Shouldn’t it always be red?