创建子类时是否需要 super?

Do i need super when creating a subclass or not?

在此程序中,不需要 super 到达超类的构造函数:

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); 
    }
}

当且仅当您的 parent class 没有默认构造函数(接受 无参数 )时,您需要调用 super() .

在所有其他情况下(存在零参数构造函数的情况),您不必对其进行编码。无论如何它都是隐式调用的。

适用这些规则:

  • 如果你的 parent class 根本没有构造函数,它有默认构造函数,它不带参数 -> 不需要 super();
  • 你 parent class 声明了一个没有参数的构造函数 -> 不需要 super()
  • 你的 class 有一个带参数的构造函数但是 没有 没有参数的构造函数 -> 你 需要 通过 super()
  • 调用带有匹配参数的已定义构造函数之一

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"); 
    }  
}

被注释掉的行是自动添加的,并且由于定义了超类的无参数构造函数,所以没有错误。

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() 试图调用超类中未定义的构造函数,这导致了错误

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

取消对显式构造函数调用的注释会替换隐式调用,从而解决问题。或者,在超类中定义一个无参数构造函数。

如果您在 super class 中创建构造函数,您应该在调用 sub class 构造函数之前调用 super class 构造函数(例如:super())。