How does the constructor work while initializing an object?

constructor, java

Solution

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

private int channel = setChannel(7);

When you do:

new Television(20);

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.

See the JLS for further and detailed information.

Problem

The output of this code is 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); } } ```

Original source