WHAT ARE DIFFERENT TYPES OF BLOCKS IN JAVA ?

Two types of blocks instance block and static block.
Initialization blocks run when the class is first loaded (a static initialization block) or when an instance is created (an instance initialization block). Let's look at an example:
class demo
{
int x=10;
{System.out.println("normal block");}
static{System.out.println("static block");}
public static void main(String[] args){
demo d=new demo();
demo d1=new demo();
System.out.println(d.x);
}}
OUTPUT:
static block
normal block
normal block
10
Static blocks are loaded first while the program is loaded and it doesnot depend upon the instances of the class.
But normal blocks are dependant upon the instances of the class it is called each time one instance is created.
Init blocks execute in the order they appear.
Instance init blocks run after the constructor's call to super().

No comments:

Post a Comment