为什么调用默认(超级)构造函数而不是空白构造函数?

-1 java inheritance constructor

在这个例子中,我有一个带有空白构造函数的子类.在超类中提供了两个构造函数.当我在下面的代码中执行main时,结果是它打印出"我是没有参数的超级构造函数".我的问题是,为什么编译器会忽略子类中的空白构造函数?如果我能接受这种"无知",那么我理解编译器将执行子类的默认构造函数,在这种情况下,它是超类中没有参数的构造函数.这是子类:

package extendisevil;

public class SubConstructorInherit extends ConstructorInherit {

  public SubConstructorInherit(String param) {

  }

  public static void main(String[] args) {

    SubConstructorInherit obj = new SubConstructorInherit("valami");

  }
}
Run Code Online (Sandbox Code Playgroud)

这是超级:

package extendisevil;

public class ConstructorInherit {

  public ConstructorInherit(String name) {
    System.out.println("I am the super constructor with String parameter: " + name);
  }

  public ConstructorInherit() {
    System.out.println("I am the super constructor without parameter.");
  }

}
Run Code Online (Sandbox Code Playgroud)

谢谢您的帮助!

tka*_*usl 7

Java并没有忽略子类的构造函数,java调用它.但是,java还必须构造每个超类,并且由于您没有在子类构造函数中调用特定的超级构造函数,因此java默认为no-arg构造函数.如果要调用除父类中的no-arg构造函数之外的任何其他构造函数,可以通过调用来执行此操作super(/* args */);,但这必须是构造函数中的第一个语句:

class Parent {
    Parent() {
        System.out.println("Parent()");
    }
    Parent(String name) {
        System.out.println("Parent(String): " + name);
    }
}

class Child extends Parent {
    Child() {
        //calls "super()" implicitly as we don't call a constructor of Parent ourselfs
        System.out.println("Child()");
    }

    Child(String name) {
        super(name); //we explicitly call a super-constructor
        System.out.println("Child(String): " + name);
    }
}

new Child();
new Child("A Name");
Run Code Online (Sandbox Code Playgroud)

打印:

Parent()
Child()
Parent(String): A Name
Child(String): A Name
Run Code Online (Sandbox Code Playgroud)

如果类不提供无参数构造函数而是提供带参数的构造函数,则子类构造函数必须显式调用给定构造函数之一.