超级构造函数是否没有超类? [英] super-constructor if there is no super class?

查看:88
本文介绍了超级构造函数是否没有超类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了一个像这样的课程:

I found a class like this:

public class Computer implements Serializable {

        private static final long serialVersionUID = 1L;    

        //...
        public Computer() {
            super();
        }
        //...
}

有人可以解释一下,这是如何工作的吗?该类没有继承任何超类,并且仍然可能存在"super();".在构造函数中?

Can someone explain me, how this works? The class isn't inheriting any super class and there could still be "super();" in the constructor?

推荐答案

默认情况下,所有类都继承java.lang.Object.因此,您班级中的隐藏代码是

By default all classes inherit java.lang.Object. So a hidden code in your class is

public class Computer extends java.lang.Object implements Serializable {

        private static final long serialVersionUID = 1L;    

        //...
        public Computer() {
            super(); //here Object's default constructor is called
        }
        //...
}

如果父类具有默认构造函数(无参数),并且子类定义了默认构造函数,则无需显式调用父类的构造函数.

If a parent class has default constructor (no argument) and if a child class defines a default constructor, then an explicit call to parent's constructor is not necessary.

Java隐式地执行此操作,换句话说,Java将super()放在孩子的构造函数的第一条语句之前

Java does it implicitly, in other words, Java puts super() before first statement of the child's constructor

考虑此示例

class Base {

    public Base() {
        System.out.println("base");
    }
}

class Derived extends Base {

    public Derived() {
        //super(); call is not necessary.. Java code puts it here by default
        System.out.println("derived");
    }
}

因此,当您创建Derived d = new Derived();时,输出是.

So when you create Derived d = new Derived(); the output is..

base
derived

这篇关于超级构造函数是否没有超类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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