Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Method executed prior to Default Constructor [duplicate]

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.

like image 591
Rohit Nigam Avatar asked Sep 21 '15 06:09

Rohit Nigam


People also ask

Can we have both default constructor and parameterized constructor in the same class in Java?

Actually you can't do that in Java, by definition. JLS §8.8.

Is it possible to call a constructor from another within the same class not from a subclass )? If yes how?

Constructor chaining can be done in two ways: Within same class: It can be done using this() keyword for constructors in the same class. From base class: by using super() keyword to call the constructor from the base class.

What is default copy constructor in Java?

A copy constructor in a Java class is a constructor that creates an object using another object of the same Java class.

Can we call constructor twice in Java?

No, there is no way to do this. Even at the JVM bytecode level, a chain of <init> methods (constructors) can be called at most once on any given object.


1 Answers

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.

like image 53
Eran Avatar answered Sep 19 '22 13:09

Eran