开发者

Super constructor not working how I think it should

开发者 https://www.devze.com 2023-04-03 13:10 出处:网络
I have a class: public abstract class LogicGate extends JPanel implements PropertyChangeListener { private Image image;

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);
}

}

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号