I have a class:
public abstract class LogicGate extends JPanel implements PropertyChangeListener {
private Image image;
private URL url;
private OutputTerminal output;
private Terminal input0;
private Terminal input1;
public LogicGate(String fileName) {
this.url = getClass().getResource(fileName);
this.image = new javax.swing.ImageIcon(url).getImage();
this.setSize(image.getWidth(null), image.getHeight(null));
this.output = new OutputTerminal();
}
}
and a subclass:
public class ANDGate extends LogicGate {
private OutputTerminal output;
private Terminal input0;
private Terminal input1;
public ANDGate() {
super("images/AND.gif");
System.out.println(this.output);
}
}
Yet when I invoke a new ANDGate object, output is null, when it should have been assigned (as per the super constructor).
Now clearly I have a made an assumption in understanding subclassing constructors; what am I doing wrong?
This situation is called field hiding – the subclass field
outputis “hiding” the field of the same name in the super class.You have defined
in both your super class and your subclass. References to
outputin the subclass will be to its field, but you’re setting output in the super class – the subclass field will remain null.To fix:
outputin the subclassoutputin the super class toprotected(so the subclass can access it)