java类对象中的默认构造函数做什么?
我是Java初学者,学习Java编译器规则如下:
- 如果类没有超类,则将其扩展到对象类
- 如果类没有构造函数,请添加默认的无参数构造函数
- 如果构造函数的第一行不是“super()”或“this()”,请添加“super()”以调用该超类的默认构造函数李>
我知道我们创建的所有对象都是从超级类对象派生的。 我的问题是对象类中的构造函数在被调用时做什么
编辑:我的问题是关于构造函数在类对象中做什么?我知道默认情况下子类调用超类的构造函数
例如,我有以下代码(其中我显式扩展到Object并调用super(),以说明编译器的功能)。我的问题是,调用super()做什么
public class Person extends Object
{
private String name;
public Person(String n)
{
super();
this.name = n;
}
}
# 1 楼答案
实际上,
Object()
什么也不做现在,您不应该将为任何子类构造函数调用
super()
(使用args或不使用args)的约束减少到没有显式扩展类的情况在这种情况下,调用
super()
似乎并不是真正有用的但是一旦一个类扩展了一个不同于
Object
的类,这个约束就非常有意义,因为子结构必须首先应用其父结构。但是语言以一种普遍的方式规定了这一点。对于直接扩展
Object
的类也不例外可能是因为,它使事情变得更简单,而这并不是一个真正的约束,因为编译器为您添加了对超级默认构造函数的调用:
super()
# 2 楼答案
它调用
java.lang.Object
的默认构造函数。回答你似乎真正想问的问题,从Java Language Specification, #8.8.9注意最后一段
# 3 楼答案
所有没有任何显式超类的Java类都从
Object
扩展,除了Object
本身。不需要在代码中显式显示,编译器会处理它此外,构造函数中的
super()
调用将调用Object
的构造函数。如果您查看实现,您将看到该对象根本没有任何构造函数,因此它将使用一个隐式空构造函数,而该构造函数不执行任何操作。构造vtable以确保继承的方法在那里使用或初始化对象的监视器等细节不是构造函数的一部分,而是在调用new
运算符时由JVM实现执行对象类有几个方法在大多数类中都很方便。例如,臭名昭著的
toString()
是在对象类中实现的。而且hashCode()
在那里实现我建议你仔细看看这个物体。类文件,以了解在每个Java类中继承了哪些方法
关于你上面的3条规则,它们在学术上是“好的”,但在现实中从未使用过。您永远不会看到显式的
extends Object
,只有在需要覆盖默认行为时才调用super()
或this()
此外,避免滥用继承并使用更多的组合(实现接口),尽管这取决于每个用例