Came across this for the first time today! Java has instance initializer blocks for initializing instance variables, similar to static inilializer blocks for static varaibles.
Order of execution of instance initializer blocks is interesting:
The above will output:
See also: http://www.javatpoint.com/instance-initializer-block
Order of execution of instance initializer blocks is interesting:
- First, any parent class constructor (called by a super method invocation in the constuctor, or the default parent class constructor) gets called.
- Then, the instance initializer block gets called.
- And after that, the remaining part of the constructor, after the super method call (if any) gets executed.
Example
class Animal{ Animal(){ System.out.println("Animal constructor called"); } } class Cat extends Animal { double whiskerLength; Cat() { super(); System.out.println("Cat constructor is executing"); } // instance initializer block { whiskerLength = 4; System.out.println("instance initializer block is executing"); } public static void main(String args[]){ Cat cat = new Cat(); } }
The above will output:
Animal constructor called instance initializer block is executing Cat constructor is executing
See also: http://www.javatpoint.com/instance-initializer-block
Comments