超级关键字没有扩展到超类 [英] super keyword without extends to the super class

查看:181
本文介绍了超级关键字没有扩展到超类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个简单的程序,在构造函数中,调用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.

这篇关于超级关键字没有扩展到超类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆