【问题标题】:Super constructor not working how I think it should超级构造函数没有按照我认为的方式工作
【发布时间】:2011-09-09 06:21:55
【问题描述】:

我有一堂课:

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

和一个子类:

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

然而,当我调用一个新的 ANDGate 对象时,output 是 null,而它本应被分配(根据超级构造函数)。

现在很明显,我在理解子类构造函数方面做了一个假设;我做错了什么?

【问题讨论】:

    标签: java oop constructor


    【解决方案1】:

    这种情况称为field hiding——子类字段output是在超类中“隐藏”同名字段。

    你已经定义了

    private OutputTerminal output;
    

    在你的超类你的子类中。子类中对 output 的引用将指向其字段,但您在超类中设置输出 - 子类字段将保持为空。

    修复:

    • 删除子类中output的声明
    • 将超类中output的声明改为protected(这样子类可以访问)

    【讨论】:

    • 好吧,一切都解决了。谢谢:D
    【解决方案2】:

    两个输出变量都是本地的每个类 他们指的是两个不同的成员。

    你宁愿删除

    private OutputTerminal output;
    

    来自class ANDGate,只需使用

    System.out.println(output);
    

    制作

    private OutputTerminal output;
    

    protected 在超类中。

    【讨论】:

      【解决方案3】:

      您可以将超类中的类变量设置为受保护,并在 system.out.println() 行中使用“super”关键字代替“this”。

      为您提供示例代码。

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

      }

      【讨论】:

        猜你喜欢
        • 2022-01-05
        • 2018-02-28
        • 1970-01-01
        • 1970-01-01
        • 2022-12-13
        • 2023-01-17
        • 2010-11-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多