超级构造函数不工作我认为它应该如何

Dom*_*mra 1 java oop constructor

我有一节课:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

和子类:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

然而,当我调用一个新ANDGate对象output时,它是null,当它应该被赋值时(根据超级构造函数).

现在很明显我在理解子类化构造函数时做了一个假设; 我究竟做错了什么?

Boh*_*ian 7

这种情况称为字段隐藏 - 子类字段output"隐藏"超类中相同名称的字段.

你定义了

private OutputTerminal output;
Run Code Online (Sandbox Code Playgroud)

在你的超类你的子类中.output子类中的引用将是其字段,但您在超类中设置输出 - 子类字段将保持为null.

修理:

  • 删除output子类中的声明
  • output将超类中的声明更改为protected(因此子类可以访问它)