有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java类对象中的默认构造函数做什么?

我是Java初学者,学习Java编译器规则如下:

  1. 如果类没有超类,则将其扩展到对象类
  2. 如果类没有构造函数,请添加默认的无参数构造函数
  3. 如果构造函数的第一行不是“super()”或“this()”,请添加“super()”以调用该超类的默认构造函数

我知道我们创建的所有对象都是从超级类对象派生的。 我的问题是对象类中的构造函数在被调用时做什么

编辑:我的问题是关于构造函数在类对象中做什么?我知道默认情况下子类调用超类的构造函数

例如,我有以下代码(其中我显式扩展到Object并调用super(),以说明编译器的功能)。我的问题是,调用super()做什么

public class Person extends Object
{
    private String name;
    public Person(String n)
        {   
            super();
            this.name = n;
        }
}

共 (3) 个答案

  1. # 1 楼答案

    For example, I have the following code (where I explicitly extend to Object and call super()). My question is, what does the call do super() do?

    实际上,Object()什么也不做
    现在,您不应该将为任何子类构造函数调用super()(使用args或不使用args)的约束减少到没有显式扩展类的情况

    在这种情况下,调用super()似乎并不是真正有用的
    但是一旦一个类扩展了一个不同于Object的类,这个约束就非常有意义,因为子结构必须首先应用其父结构。

    但是语言以一种普遍的方式规定了这一点。对于直接扩展Object的类也不例外
    可能是因为,它使事情变得更简单,而这并不是一个真正的约束,因为编译器为您添加了对超级默认构造函数的调用:super()

  2. # 2 楼答案

    My question is, what does the call to super() do?

    它调用java.lang.Object的默认构造函数。回答你似乎真正想问的问题,从Java Language Specification, #8.8.9

    8.8.9. Default Constructor

    If a class contains no constructor declarations, then a default constructor is implicitly declared. The form of the default constructor for a top level class, member class, or local class is as follows:

    The default constructor has the same accessibility as the class (§6.6).

    The default constructor has no formal parameters, except in a non-private inner member class, where the default constructor implicitly declares one formal parameter representing the immediately enclosing instance of the class (§8.8.1, §15.9.2, §15.9.3).

    The default constructor has no throws clauses.

    If the class being declared is the primordial class Object, then the default constructor has an empty body. Otherwise, the default constructor simply invokes the superclass constructor with no arguments.

    注意最后一段

  3. # 3 楼答案

    所有没有任何显式超类的Java类都从Object扩展,除了Object本身。不需要在代码中显式显示,编译器会处理它

    此外,构造函数中的super()调用将调用Object的构造函数。如果您查看实现,您将看到该对象根本没有任何构造函数,因此它将使用一个隐式空构造函数,而该构造函数不执行任何操作。构造vtable以确保继承的方法在那里使用或初始化对象的监视器等细节不是构造函数的一部分,而是在调用new运算符时由JVM实现执行

    public Object() {
    
    }
    

    对象类有几个方法在大多数类中都很方便。例如,臭名昭著的toString()是在对象类中实现的。而且hashCode()在那里实现

    我建议你仔细看看这个物体。类文件,以了解在每个Java类中继承了哪些方法

    关于你上面的3条规则,它们在学术上是“好的”,但在现实中从未使用过。您永远不会看到显式的extends Object,只有在需要覆盖默认行为时才调用super()this()

    此外,避免滥用继承并使用更多的组合(实现接口),尽管这取决于每个用例