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);
}
}
When you create an object, you are creating an instance of a class, therefore "instantiating" a class. The new operator requires a single, postfix argument: a call to a constructor. The name of the constructor provides the name of the class to instantiate. The constructor initializes the new object.
Declaration: The code set in bold are all variable declarations that associate a variable name with an object type. Instantiation: The new keyword is a Java operator that creates the object. Initialization: The new operator is followed by a call to a constructor, which initializes the new object.
A constructor in Java is a special method that is used to initialize objects.
Assigning value to a variable is called initialization of state of an object. Initialization of variable means storing data into an object. 3. We can assign the value of variables in three ways: by using constructor, reference variable, and method.
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.
Because that's the order of initialization in Java. In short:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With