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.
Actually you can't do that in Java, by definition. JLS §8.8.
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.
A copy constructor in a Java class is a constructor that creates an object using another object of the same Java class.
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.
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.
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