Reputation: 1970
I'm not able to get exactly why this code gives an output 0?
public class Poly
{
public static void main(String[] args)
{
Square sq=new Square(10);
}
}
class Square
{
int side;
Square(int a)
{
side=a;
}
{
System.out.print("The side of square is : "+side);
System.out.println();
}
}
What I want to ask-
Why it is showing output 0,and not 10?
Why Instance Initialization Block is initializing first and then constructors?
Upvotes: 0
Views: 129
Reputation: 96444
It's not an instance initializer's job to completely initialize the whole object, you can have multiple initializers that each handle different things. When you have multiple initialization blocks they run in the order in which they appear in the file, top-to-bottom, and they cannot contain forward references. This article by Bill Venners has a lot of useful detail.
On the other hand, a constructor is responsible for initializing the entire object. Once the constructor has run the object is initialized, it should be in a valid state and be ready to be used.
So if an instance initializer ran after the constructor it wouldn't be initializing, it would be changing something that was already set. So the initializers have to run before the constructor.
Upvotes: 3
Reputation: 563
Order is something like this, the static blocks go first and then the non static blocks. Then the Constructor.
Upvotes: 0