【问题标题】:Parent and child parameterized constructor in JavaJava中的父子参数化构造函数
【发布时间】:2019-11-29 12:34:39
【问题描述】:

Java中父子构造函数的正常测试,所以我在父子类中都使用参数化构造函数,
但我没有得到正确的输出。

class A {

    A(int i) {
        System.out.println(i);
    }
}



class B extends A {

    B(int i, int j) {
        System.out.println(i+j);
    }
}



public class Test {

    public static void main(String args[]) {    
        B b = new B(5,7);
    }
}

【问题讨论】:

  • 一开始就在B构造函数中添加super(i);。下次请说明什么是“正确的输出”
  • 那你得到了什么?
  • 你期待什么输出
  • 您的代码无法编译。这与“我没有得到正确的输出”不同。

标签: java inheritance constructor


【解决方案1】:

Class B 扩展了具有非空构造函数的 Class A
所以当我们尝试构造Class B的实例时,应该先调用父构造函数
通过调用super(...)关键字

super(integerValue);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-03
    • 2021-03-12
    • 2018-02-28
    • 1970-01-01
    • 2018-01-31
    • 2016-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多