0

我无法理解以下代码中的控制流程:

class Television {
    private int channel=setChannel(7);

    public Television (int channel) {
        this.channel=channel;
        System.out.println(channel + "");
    }

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

public class TelevisionMain {
    public static void main(String[] args) {
        Television t = new Television(12);
    }
}

输出为 7 12。

这意味着首先发生显式调用。我是java新手,我认为执行从main开始,所以应该首先调用构造函数。谁能解释一下为什么会这样。

4

4 回答 4

2

初始化是构造的一部分,它被定义为在调用 super() 之后和构造函数主体之前发生。

应该首先调用构造函数。

这是。字段初始化是构造函数的一部分。

于 2013-11-01T20:09:02.177 回答
1

您的Television构造函数大致编译为:

public Television(int channel)
{
    super();
    this.channel = this.setChannel(7);
    this.channel = channel;
    System.out.println(channel+"");
}

因此,当您调用 时Television t = new Television(12);,它首先将频道设置为 7,然后设置为 12。

于 2013-11-01T20:10:50.920 回答
0

最终答案是因为规范说它应该。然而,这种方式是合理的,因为反之则无法覆盖默认的初始值

如果订单首先是构造函数,然后是其他所有内容,那么订单将是

  • 叫电视(12)
  • 通道在构造函数中设置为 12
  • 通过 int channel=setChannel(7)将通道设置回7;

这显然是一种不合理的情况,因为您永远不能使用默认值,因为这些默认值不能被构造函数更改

于 2013-11-01T20:09:56.853 回答
0

在 Java 中,本质上是一个隐藏的默认构造函数。如果你不声明一个,你可以在一个类的顶部用一个默认变量初始化一个变量。无论如何,这就是我们喜欢思考的方式。现实情况是,每个类都有一个静态块,在类加载过程中实际构造函数声明命中之前,可以在其中声明和播放变量。

我觉得您的上述声明与此类似,这就是您看到输出 7 12 的原因。

class Television {
   //The below code is essentially equal to your declaration of
   // private int channel = setChannel(7);
   private int channel;
   static{
       //This occurs before constructor call during class load.
       channel = setChannel(7);
   }
   ....
}

可以在有关初始化字段的 java 教程中找到更好的解释

于 2013-11-01T20:11:56.883 回答