gpt4 book ai didi

java - 创建子类时是否需要 super ?

转载 作者:行者123 更新时间:2023-11-30 07:43:09 24 4
gpt4 key购买 nike

在此程序中,不需要 super 来访问父类(super class)的构造函数:

class Base{

Base(){

System.out.println("Base");
}
}

public class test2 extends Base{

test2() {

//super();
System.out.print("test2");
}

public static void main(String argv[]){

test2 c = new test2();
}
}

但是这个程序需要 super 并在 quest1 构造函数中给出错误

constructor quest can't be applied to given types: required int, found no arguments

class Quest {

Quest(int y){

System.out.print("A:"+y);
}
}

class Quest1 extends Quest {

Quest1(int x){

//super(x+1);
System.out.print("B:"+x);
}
}

class Test {

public static void main(String argv[]){

Quest1 q = new Quest1(5);
}
}

最佳答案

JLS 8.8.7. Constructor Body

If a constructor body does not begin with an explicit constructor invocation and the constructor being declared is not part of the primordial class Object, then the constructor body implicitly begins with a superclass constructor invocation "super();", an invocation of the constructor of its direct superclass that takes no arguments.

class Base {

Base() {

}
}

public class test2 extends Base {

test2() {

//super();
System.out.print("test2");
}
}

注释掉的行是自动添加的,并且由于定义了父类(super class)的无参构造函数,因此不会出现错误。

如果是

class Quest {

Quest(int y) {

System.out.print("A:"+y);
}
}

class Quest1 extends Quest {

Quest1(int x) {

//super(x+1);
System.out.print("B:"+x);
}
}

隐式调用super()试图调用父类(super class)中未定义的构造函数,这会导致错误

Implicit super constructor Quest() is undefined. Must explicitly invoke another constructor.

取消注释显式构造函数调用将替换隐式调用,从而解决问题。或者,在父类(super class)中定义一个无参构造函数。

关于java - 创建子类时是否需要 super ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34371593/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com