super-constructor if there is no super class?(如果没有超类,超构造函数?)
问题描述
我找到了这样一个类:
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
这篇关于如果没有超类,超构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如果没有超类,超构造函数?
基础教程推荐
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01