0

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-

  1. Why it is showing output 0,and not 10?

  2. Why Instance Initialization Block is initializing first and then constructors?

Frosted Cupcake
  • 1,909
  • 2
  • 20
  • 42
  • 1
    Because the JLS designers flipped a coin and said initializers should come before their respective constructors.. – Jeroen Vannevel Sep 09 '15 at 14:24
  • move your static initializer code as a method. And call that method later on from main method after constructor call. – Raman Shrivastava Sep 09 '15 at 14:26
  • 1
    @JeroenVannevel Sort of, but it must have been a slightly biased coin. Probably more people feel it "natural" for it to work in this order than the other way around. (Particularly with regards to field initialisation.) – biziclop Sep 09 '15 at 14:30

2 Answers2

3

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.

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
0

Order is something like this, the static blocks go first and then the non static blocks. Then the Constructor.

Dhana
  • 505
  • 1
  • 8
  • 27