super keyword without extends to the super class

故事扮演 提交于 2019-11-27 07:00:59

问题


There is a code of simple program. In 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));
    }

}

回答1:


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

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.




回答2:


There is not need to add super() because it is by default added.

It will call Object class's default constructor because in JAVA every class extends Object by default.




回答3:


Constructor from your code works the same as:

Student(String name, int rollNum){
    this.name = name;
    this.rollNum = rollNum;
}

In your question super() is just calling constructor of Object class.



来源:https://stackoverflow.com/questions/23441481/super-keyword-without-extends-to-the-super-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!