构造函数在初始化对象时如何工作?

2023-12-28

这段代码的输出是 7 20。

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

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);
    }
}

当对象被创建时,它的字段也被创建。你有一个班级成员:

private int channel = setChannel(7);

当你这样做时:

new Television(20);

该字段已初始化并且setChannel在调用构造函数之前调用,并从那里打印 7。

的所有领域object创建并填充提供的值(如果未指定值,则使用默认值)。您可以将其视为实例的准备。这些成员准备好并初始化后,调用构造函数。

See the JLS http://docs.oracle.com/javase/specs/jls/se8/html/jls-12.html#jls-12.4以获得更多详细信息。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

构造函数在初始化对象时如何工作? 的相关文章

随机推荐