class B {
{
System.out.println("IIB B");
}
B(int i) {
System.out.println("Cons B int");
}
public B() {
this(10);
System.out.println("Cons B");
}
}
public class C extends B {
{
System.out.println("IIB C");
}
public C() {
System.out.println("Cons C");
}
public static void main(String[] args) {
C c1 = new C();
}
}
Output
IIB B
Cons B int
Cons B
IIB C
Cons C
As per Oracle tutorials ,
"The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors."
So why initializer blocks of class B is not executed twice as constructor is executing twice?
So why initializer blocks of class B is not executed twice as constructor is executing twice?
No, the constructor runs only once. Delegating work to another constructor is taken into account by the compiler and the instance initializers are not copied into a constructor which begins with a this()
invocation.
In general, you don't need to bother reasoning about where exactly the instance initializer code is copied. Simply rely on the fact that it will run once and only once for each object initialization.
The moment at which instance initializers run is immediately after completing the super()
constructor call.
The link you include in your question is not the Javadocs, but an Oracle Tutorial. There is a very important difference between these two: Javadocs are normative whereas the tutorials are only descriptive. Some wording in the tutorials may be imprecise as a compromise between teaching value and factual accuracy.
If you ever have a doubt about something you have read in a tutorial, then try to find the authoritative statement in the Java Language Specification or the JDK Javadoc.
You have created only one instance of B
.i.e. an instance of C
. so, it will get printed only once since the constructor runs only once. Try creating another instance of C
, then you will get it printed twice.
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