首页 > 解决方案 > 下面是代码片段和错误消息,为什么编译器要求这个默认构造函数?

问题描述

class X{
    X(){
        System.out.println("Inside X()");
    }
    X(int x){
        System.out.println("Inside X(int)");
    }
}
class Y extends X{
    Y(String s){
        System.out.println("Inside Y(String)");
    }
    Y(int y){
        super(1000);
        System.out.println("Inside Y(int)");
    }
}
class Z extends Y{
    Z(){
        System.out.println("Inside Z()");
    }
    Z(int z){
        super(100);
        System.out.println("Inside Z(int)");
    }
}
public class Program{
    public static void main(String args[]){
        Z z=new Z(10);
    }
}

上面的代码在编译时给出以下错误:-

Program.java:23:错误:没有为 Y 找到合适的构造函数(无参数)

Z(){
   ^
constructor Y.Y(String) is not applicable

  (actual and formal argument lists differ in length)

constructor Y.Y(int) is not applicable

  (actual and formal argument lists differ in length)

1 个错误

当我们调用参数化构造函数时,默认构造函数有什么用,java编译器给出错误我无法理解为什么需要这个默认构造函数?

标签: java

解决方案


如果它没有没有参数的构造函数(默认一个),则需要指定用于创建超类的构造函数*

构造函数中的第一个语句是调用,super()除非您使用任何参数显式调用 this 或 super。该super()调用由 java 在编译时注入。因此它在 Y 类中寻找非参数构造函数。

请参考文档

注意:如果构造函数没有显式调用超类构造函数,Java 编译器会自动插入对超类的无参数构造函数的调用。如果超类没有无参数构造函数,则会出现编译时错误。Object 确实有这样的构造函数,所以如果 Object 是唯一的超类,则没有问题。

在实践中,编译器会预处理您的代码并生成如下内容:

class X{
    X(){
        super(); // Injected by compiler
        System.out.println("Inside X()");
    }
    X(int x){
        super(); // Injected by compiler
        System.out.println("Inside X(int)");
    }
}
class Y extends X{
    Y(String s){
        super(); // Injected by compiler
        System.out.println("Inside Y(String)");
    }
    Y(int y){
        super(1000);
        System.out.println("Inside Y(int)");
    }
}
class Z extends Y{
    Z(){ 
        super(); // Injected by compiler
        System.out.println("Inside Z()");
    }
    Z(int z){
        super(100);
        System.out.println("Inside Z(int)");
    }
}
public class Program{
    public static void main(String args[]){
        Z z=new Z(10);
    }
}

然后它将继续编译它,但是如您所见,Z 非参数构造函数尝试引用 Y 非参数构造函数,它不存在。

*正如 Carlos Heuberger 所澄清的那样。


推荐阅读