Anonymous/Unnamed code blocks in Java
Anonymous code blocks in java are used to write common code for every constructor of a class. Syntax for the anonymous code blocks looks like this :
{
//Common code goes here.
}These blocks are called as instance initialization blocks.
These blocks don’t have any name and are called for every constructor in the class. These blocks are called before a constructor is called.
Here’s an example
class Demo{
public Demo(){
System.out.println("default constructor");
}
public Demo(int i){
System.out.println("parameterized constructor");
}
{
System.out.print("Object is created by the ");
}
public static void main(String arr[]){
Demo b1 = new Demo();
Demo b2 = new Demo(1);
}
}Output of the code:
Object is created by the default constructor
Object is created by the parameterized constructorIn the above you example you can see that the print statement in the anonymous block was called before calling the constructor for each constructor in the class.
I use this to create logs for every constructor.
Comments
Post a Comment