Saturday, July 23, 2016

This block - Instance Initializer Block – (IIB) - instance initializers

This block, also known as instance initializer block is used for initializing instance data member (instance variable – non static variables).
This block will execute each time for each object creation for the class. This is invoked before the constructor of the class are invoked.
Example :
public class ThisIntializer extends ThisSuper {
               
{
                System.out.println("ThisIntializer : Subclass this block 1........");
}

ThisIntializer() {

                System.out.println("ThisIntializer : Subclass Constructor .......");

}
{
System.out.println("ThisIntializer : Subclass this block 2........");
}
public static void main(String[] args) {
                               
System.out.println("--------- Creating first Object o1 ----------");

                                ThisIntializer o1 = new ThisIntializer();

System.out.println("--------- Creating first Object o2 --------------");

                                ThisIntializer o2 = new ThisIntializer();
}

}

class ThisSuper {
                {
                System.out.println("ThisSuper : Super class This Block ....");
                }
                ThisSuper () {

                System.out.println("ThisSuper : Super Class constructor ......");

                }
}

---------------------------Output -------------------------------------------

--------- Creating first Object o1 ----------
ThisSuper : Super class This Block ....
ThisSuper : Super Class constructor ......
ThisIntializer : Subclass this block 1........
ThisIntializer : Subclass this block 2........
ThisIntializer : Subclass Constructor .......

--------- Creating first Object o2 --------------
ThisSuper : Super class This Block ....
ThisSuper : Super Class constructor ......
ThisIntializer : Subclass this block 1........
ThisIntializer : Subclass this block 2........
ThisIntializer : Subclass Constructor .......

-----------------------------End of Output-----------------------------------

Things to Know:

1.       instance initializer will call for Each Object creation (i.e each time when the instance of the class is created)
2.       Like Constructor, for instance initializer also super class instance initializer will execute first.
ie. Super class this block à super constructor --> subclass this block --> subclass constructor
3.       The java compiler copies the code of instance initializer block in every constructor.
For compiler code for ThisIntializer constructor will be look as below :
ThisIntializer() {

       Super()
{
                System.out.println("ThisIntializer : Subclass this block 1........"); 
   }

        System.out.println("ThisIntializer : Subclass Constructor .......");

}

4.       If 1 or more this block present in the program then the order for executing this block will be , the order in which they appears in the program.
5.       We can’t return anything from ‘instance initializer’. i.e ‘return’ are not allowed inside instance initializer.
But we can throw a checked exception from instance initializer ( only if the checked exceptions are explicitly declared in the throws clause of every constructor in the class).


------------------------------------------------------------------------------------------------------------------------------------------


Where to use and why?

1.       If you want to do some operation before assigning values to instance data members (instance variables). Like array, List initialization or for doing complex calculation.
2.       For doing error handling by catching exceptions and using finally.

The above two scenario we will be able to do in constructor also, but if the class is having more than one constructor, we would have to repeat this code in each constructor.

3.       As a initializer for anonymous inner classes.(we can’t declare any constructor inside the  anonymous inner classes). Instance initializers in anonymous inner classes can throw any exception.


The below Code is having compilation Error:

public class innerClass {
                StringReader reader = null;
    {
                reader = new StringReader(new String("test"));
        try {
                reader.read();
                                } catch (IOException e) {
                                throw e; // compilation error
                                               
                                }
    }
    innerClass() {
               
    }
               
public static void main(String[] args) throws IOException {
innerClass i = new innerClass();

}

Corrected Code :

public class innerClass {
                StringReader reader = null;
    {
                reader = new StringReader(new String("test"));
        try {
                reader.read();
                                } catch (IOException e) {
                                throw e;                                               
                                }
    }
    innerClass() throws IOException {
               
    }
                /**
                 * @param args
                 * @throws IOException
                 */
                public static void main(String[] args) throws IOException {
                                innerClass i = new innerClass();
}



Example for anonymous inner classes

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class innerClass {
                StringReader reader = null;
    {
                reader = new StringReader(new String("test"));
        try {
                reader.read();
                                } catch (IOException e) {
                                throw e;
                                               
                                }
    }
    innerClass() throws IOException {
               
    }
                /**
                 * @param args
                 * @throws IOException
                 */
                public static void main(String[] args) throws IOException {
                                innerClass i = new innerClass();
                                // TODO Auto-generated method stub
                                                new Thread(new Runnable(){
                                                                Path file = Paths.get("./test.txt");
                                                                {                                                              
                                                                                try{
                                                                                InputStream in = Files.newInputStream(file);
                                                                    BufferedReader reader =
                                                                      new BufferedReader(new InputStreamReader(in));
                                                                    String line = null;
                                                                    while ((line = reader.readLine()) != null) {
                                                                        System.out.println(line);
                                                                    }
                                                                } catch (IOException x) {
                                                                    System.err.println(x);
                                                                }
                                                                }
                                                                @Override
                                                                public void run() {
                                                                                System.out.println("run ");
                                                                               
                                                                }

                                                  
                                                }).start();
                               
                }

}

For more FAQ on instance initializer block, please refer  IIB FAQ

No comments:

Post a Comment