Sunday, 9 February 2014

initializer blocks

Initializer blocks are used to initialize instance variables.

    Syntax of Initializer Blocks
    {
        //initialization Blocks code goes here
    }

Java compiler copies initializer blocks into every constructor.

Example
class Box{
 int width,height;
 
 {
  width = 10;
  height = 15;
 }

 public static void main(String args[]){
  Box b1 = new Box();
  System.out.println(b1.width +"\t"+b1.height);
 }
}
      

Output
 10 15
      
Some Points to Remember
1. A class can have more than one initializer block
class Box{
 int width,height;
 String name;
 
 {
  width = 10;
  height = 15;
 }
 
 {
  name = "My Box";
 }

 public static void main(String args[]){
  Box b1 = new Box();
  System.out.println(b1.width +"\t"+b1.height);
  System.out.println(b1.name);
 }
}

Output
10 15
My Box

2. The data in initializer blocks copied to every constructor
Example
class Box{
 int width,height;
 String name;

 {
  width = 10;
  height = 15;
 }

 {
  name = "My Box";
 }

 Box(){

 }

 Box(int w){
  width = w;
 }
 
 public static void main(String args[]){
  Box b1 = new Box();
  Box b2 = new Box(100);
  
  System.out.println(b1.width +"\t"+b1.height);
  System.out.println(b1.name);
  System.out.println(b2.width +"\t"+b2.height);
  System.out.println(b2.name);
 }
}

Output
10 15
My Box
100 15
My Box


3. Initializer block are called every time, when you created the object
      Example  
class Person{
 {
  System.out.println("I am first");
 }

 {
  System.out.println("I am second");
 }

 public static void main(String args[]){
  Person p1 = new Person();
  Person p2 = new Person();
 }
}

Output
I am first
I am second
I am first
I am second

4. Initializing static fields in the initialization block is valid, but don't use it, since the static variable is initialized every time when a new object created.
Example
class Person{
 static int minSalary;
 
 {
  minSalary = 10000;
 }

 public static void main(String args[]){
  Person p1 = new Person();
  Person.minSalary = 50000;
  System.out.println(Person.minSalary);
  
  Person p2 = new Person();
  System.out.println(Person.minSalary);
 }
}

Output
50000
10000
      


Static Methods                                                 Static Blocks                                                 Home

No comments:

Post a Comment