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.
}
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);
}

}
Object is created by the default constructor
Object is created by the parameterized constructor

Comments

Popular posts from this blog

26th September - Day 15 of writing Diary

Day 2 of writing Diary

6th October Day 25 of writing Diary