超级关键字没有扩展到超类

超级关键字没有扩展到超类

问题描述:

有一个简单的程序,在构造函数中,调用super()而不扩展到超类,我无法理解在这种情况下会做什么?

There is a simple program, in the constructor, super() is called without extends to the super class, I can not understand what will does this in this situation ?

public class Student {

    private String name;
    private int rollNum;

    Student(String name,int rollNum){
        super();// I can not understand why super keyword here.
        this.name=name;
        this.rollNum=rollNum;
    }


    public static void main(String[] args) {

        Student s1 = new Student("A",1);
        Student s2 = new Student("A",1);

        System.out.println(s1.equals(s2));
    }

}


每个未显式扩展另一个类的类都会隐式扩展 java.lang.Object 。所以 super()只需调用Object的no-arg构造函数。

Every class that doesn't explicitly extend another class implicitly extends java.lang.Object. So super() simply calls the no-arg constructor of Object.

注意这个显式调用是不必要的,因为编译器会为你添加它。当你想要调用带参数的超类构造函数时,你只需要在构造函数中添加一个 super()调用。

Note that this explicit call is unnecessary since the compiler would add it for you. You only need to add a super() call in a constructor when you want to invoke a superclass constructor with arguments.