简体   繁体   中英

Super constructor not working how I think it should

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 output is "hiding" the field of the same name in the super class.

You have defined

private OutputTerminal output;

in both your super class and your subclass. References to output in the subclass will be to its field, but you're setting output in the super class - the subclass field will remain null.

To fix:

  • delete the declaration of output in the subclass
  • change the declaration of output in the super class to protected (so the subclass can access it)

Both output variables are local each class they refer to two different members.

you rather remove

private OutputTerminal output;

from class ANDGate and simply use

System.out.println(output);

Make

private OutputTerminal output;

protected in super class.

You can make the class variable in super class as protected and use 'super' keyword instead of 'this' in the system.out.println() line.

Example code for you.

//superclass
class A {
protected int a;

public A(){
    a=50;
}
}

//sublcass
class B extends A{

private int a;

public B(){
    super();
    System.out.println(super.a);
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM