【问题标题】:Why do I get a 'constructor is undefined` error?为什么我会收到“构造函数未定义”错误?
【发布时间】:2015-07-12 12:37:50
【问题描述】:

为什么下面的代码会产生编译错误(构造函数AA() 未定义)?它不应该调用默认构造函数吗?

public class A{
    public A(){ }
}

public class AA extends A{
    public AA(int aa){ }
}

public class C{
    public static void main(String[] args){
        A a= new AA();
    }
}

【问题讨论】:

  • AA还有其他构造函数吗?
  • @Eran 是的,我编辑了代码。

标签: java


【解决方案1】:

如果class 中没有构造函数,编译器只会将默认构造函数添加到class,而AA 不是这种情况。

8.8.9 Default Constructors (Java language specification)

如果类不包含构造函数声明,则隐式声明默认构造函数

【讨论】:

    【解决方案2】:

    你写

    A a= new AA(); // try to invoke default constructor
    

    但是AA类中没有default构造函数,因为你自己写了构造函数

    public AA(int aa){ }
    

    所以试试这个:

    int someInteger = 1;
    A a= new AA(someInteger);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-30
      • 2012-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多