Reputation: 21
I have kind of code. And I want to know why "block b" running first, but not "constructorb". The same thing at Class A. Thanks.
class B {
B() {
System.out.println("constructorb");
}
{
System.out.println("block b");
}
}
class A extends B {
A() {
super();
System.out.println("constructor a");
}
{
System.out.println("block a");
}
public static void main(String[] args) {
A a = new A();
}
}
output:
block b
constructorb
block a
constructor a
Upvotes: 0
Views: 53
Reputation: 534
It is a normal Object instance initialization process.
There are two principles in the process of instance initialization:
static method
would run before constructor method
.parent class
would run before child class
.Now, you have parent class
named B
, and child class
named A
extends B.
So, the class B
should run before class A
.
Next. In class B
, you define a static method
which is
{
System.out.println("block b");
}
So, the string block b
is printed first. And then constructor method runs:
B() {
System.out.println("constructorb");
}
So, the string constructorb
is printed second.
Now, class B
runs finish. And then class A
runs as the order static mehod
first and constructor method
second.
Upvotes: 0
Reputation: 45866
Instance initializers (i.e. the {}
blocks) are effecitvely, if not literally, folded into the constructor. The same thing happens with field initialization. Both instance initializers and field initializations are inserted just after the super(...)
constructor call (whether implicit or explicit) but before the rest of the constructor code. So when you have:
public class Foo {
private int bar = 5;
{
System.out.println("Instance initializer");
}
public Foo() {
System.out.println("Constructor");
}
}
It's compiled as if the following was written:
public class Foo {
private int bar;
public Foo() {
super();
this.bar = 5;
System.out.println("Instance initializer");
System.out.println("Constructor");
}
}
The order that fields are initialized and instance initializers are executed is, however, determined by their order in the source code. But note that the placement of the constructor is irrelevant.
This is described in §8.8.7.1 of the Java Language Specification.
Upvotes: 1
Reputation: 1340
It is because block a
is in a non-static block. A non-static block executes when the object is created, before the constructor
Upvotes: 0