33

I'm learning java and accidentally I came across following code where default constructor is executed after the method.

public class ChkCons {

    int var = getVal();

    ChkCons() {
        System.out.println("I'm Default Constructor.");
    }

    public int getVal() {
        System.out.println("I'm in Method.");
        return 10;
    }

    public static void main(String[] args) {

        ChkCons c = new ChkCons();

    }

}

OUTPUT :

I'm in Method.
I'm Default Constructor.

Can anyone please explain me why this happened?

Thanks.

Rohit Nigam
  • 708
  • 8
  • 23

6 Answers6

41

Instance variable initialization expressions such as int var = getVal(); are evaluated after the super class constructor is executed but prior to the execution of the current class constructor's body.

Therefore getVal() is called before the body of the ChkCons constructor is executed.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • Alright, then getVal() will it execute before the STATIC BLOCK also? – Rohit Nigam Sep 21 '15 at 06:34
  • 1
    @RohitNigam No, the static initializer block is executed when the class is initialized. That takes place before any individual instance of the class is initialized. – Eran Sep 21 '15 at 06:39
  • 1
    @RohitNigam How could it? It requires *an instance*. There's no instance in a static block. Just think about it for a second. – Luaan Sep 21 '15 at 08:32
  • 1
    @Holger Perhaps my wording was inaccurate. I meant the instance variable initializations take place before the code of the current class's constructor is executed. I said nothing about when the code of the super class's constructor is executed. – Eran Sep 21 '15 at 12:09
  • you should keep `getVal()` as a static method. – Ankit Deshpande Sep 26 '15 at 19:01
  • The wording is incorrect, as noted by @Holger, and should be fixed *in the answer*. Clarifying in comments is not sufficient. – user207421 May 11 '18 at 04:41
6

Constructor is called prior to method. The execution of method occurs after that which is a part of object creation in which instance variables are evaluated. This could be better understand from following code.

class SuperClass{
    SuperClass(){
        System.out.println("Super constructor");
    }
}
public class ChkCons extends SuperClass{

    int var = getVal();

    ChkCons() {
        System.out.println("I'm Default Constructor.");
    }

    public int getVal() {
        System.out.println("I'm in Method.");
        return 10;
    }

    public static void main(String[] args) {

        ChkCons c = new ChkCons();

    }

}

The above code has following output

Super constructor
I'm in Method.
I'm Default Constructor.

Here the compiler automatically adds super(); as the first statement in ChkCons() constructor, and hence it is called prior to the getVal() method.

prateek tomar
  • 362
  • 1
  • 12
2

We can refer the following oracle documentation on Initializing instance variables (Emphasis is mine):

Initializing Instance Members

Normally, you would put code to initialize an instance variable in a constructor. There are two alternatives to using a constructor to initialize instance variables: initializer blocks and final methods.

Initializer blocks for instance variables look just like static initializer blocks, but without the static keyword:

{ // whatever code is needed for initialization goes here }

> The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.

A final method cannot be overridden in a subclass. This is discussed in the lesson on interfaces and inheritance. Here is an example of using a final method for initializing an instance variable:

class Whatever {
private varType myVar = initializeInstanceVariable();

protected final varType initializeInstanceVariable() {

    // initialization code goes here
} 
}

https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html

Vasu
  • 21,832
  • 11
  • 51
  • 67
1

Whenever you create an instance of a class instance variables are initialized first followed by execution of the Constructor

Ref : Are fields initialized before constructor code is run in Java?

Community
  • 1
  • 1
Rahman
  • 3,755
  • 3
  • 26
  • 43
1
public class InitializerIndex {

    public InitializerIndex() {
        // TODO Auto-generated constructor stub
        System.out.println("Default Constructor");
    }

    static {

        System.out.println("Static Block one");
    }

    {
        System.out.println("Init one");
    }

    void letsRoll() {

    }

    public static void main(String[] args) {
        new InitializerIndex().letsRoll();
        new InitializerIndex().letsRoll();
    }

    {
        System.out.println("Init Two");
    }

    static {
        System.out.println("Static Block two");
    }

}

Will have following output:

Static Block one
Static Block two
Init one
Init Two
Default Constructor
Init one
Init Two
Default Constructor

First all the static content is loaded, then the instance content. Static content is loaded only once.

Even when two objects are created, the static block is called only when the first object is created.

Also, at the time of object creation or in constructors, if you want to use methods like this

 int var = getVal();

You should use static methods.

gnat
  • 6,213
  • 108
  • 53
  • 73
Ankit Deshpande
  • 3,476
  • 1
  • 29
  • 42
0

It's because you are initializing the method into a field using int var = getVal();, so it will execute before constructor call. Static block have the first priority, it executes during loading of class.

SSP
  • 2,650
  • 5
  • 31
  • 49
rohithrkrk
  • 29
  • 1
  • 10