构造函数在初始化对象时如何工作? [英] How does the constructor work while initializing an object?

查看:95
本文介绍了构造函数在初始化对象时如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码的输出为720。

The output of this code is 7 20.

为什么先打印7个,然后打印20个?

Why does 7 print first and 20 is printed after that?

public class Television 
{
    private int channel = setChannel(7);
    public Television(int channel) 
    {
        this.channel = channel;
        System.out.print(channel +"");
    }

    public int setChannel(int channel) 
    {
        this.channel = channel;
        System.out.print(channel + "");
        return channel;
    }

    public static void main(String args[])
    {
        new Television(20);
    }
}


推荐答案

何时创建对象,创建其字段。您有一个班级成员:

When the object is created, its fields are created. You have a class member:

private int channel = setChannel(7);

当您这样做时:

new Television(20);

该字段已初始化,并调用了 setChannel

The field is initialized and setChannel is called before calling the constructor and 7 gets printed from there.

对象的所有字段均已创建,并使用提供的值(或默认值)进行填充(如果未指定任何值)。您可以将其视为实例的准备。这些成员准备就绪并初始化后,将调用构造函数。

All fields of the object are created and populated with the provided values (or default values if no value is specified). You can think of that as preparation of the instance. After these members are ready and initialized, the constructor is called.

请参见JLS 了解更多详细信息。

See the JLS for further and detailed information.

这篇关于构造函数在初始化对象时如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆