Dominic Bou-Samra
Dominic Bou-Samra

Reputation: 15406

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?

Upvotes: 1

Views: 703

Answers (3)

Jayy
Jayy

Reputation: 2436

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

}

Upvotes: 1

Amritpal Singh
Amritpal Singh

Reputation: 1785

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.

Upvotes: 3

Bohemian
Bohemian

Reputation: 424983

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)

Upvotes: 7

Related Questions