如果没有超类,超构造函数?

2022-01-24 00:00:00 polymorphism java

我找到了这样一个类:

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

相关文章