Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the constructor work while initializing an object?

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);
    }
}
like image 648
varun Avatar asked Apr 24 '14 08:04

varun


People also ask

How does a constructor initialize an object?

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.

How does a constructor initialize an object in Java?

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.

Are constructors used for initialization?

A constructor in Java is a special method that is used to initialize objects.

What happens when you initialize an object?

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.


2 Answers

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.

like image 141
Maroun Avatar answered Oct 17 '22 20:10

Maroun


Because that's the order of initialization in Java. In short:

  1. Static members and blocks
  2. Instance members and blocks
  3. Contructor body
like image 14
endriu_l Avatar answered Oct 17 '22 21:10

endriu_l