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
这篇关于如果没有超类,超构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如果没有超类,超构造函数?


基础教程推荐
- RabbitMQ:消息保持“未确认"; 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01