如果没有超类,超构造函数? [英] super-constructor if there is no super class?

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

问题描述

我找到了这样一个类:

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() 放在子构造函数的 first statement 之前

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天全站免登陆