Show Mobile Navigation

Webring

Powered by WebRing.

Intialization blocks in java:static and instance initialization blocks

Sachin R Kukale - 02:09
Initialization blocks are used to initialize the members of class and objects in Java. There are two types of initialization blocks in Java:
i. Static Block:
Static blocks are used to initialize the static members of that particular class. Static block are initialized at the time loading of class in JVM. A class will be initialized before instance creation of block if it has static members declared inside it.
If there are more than one static blocks then order of execution of these block will depend on order in which they are initialized in the source code.
Static blocks are those blocks which are initialized inside a class but outside any other member of class..
If there is inheritance relation between two classes then static block of parent class will be initialized before the static block of child class.
You must ‘static’ keyword in order to create a static block in Java
Syntax:
static{
//statement(s).
}
ii. Instance Block:
Instance blocks are those blocks which are declared inside a class but outside the any member of class without ‘static’ keyword.
Instance blocks are used to initialize the instance members of class. You can define more than one instance blocks in a class and in this case the order of execution will depend on the textual order in which they are created in source file.
The main advantage of using instance class is that they can be used to centralize the code and thus instance blocks helps to avoid the problem of code duplication.
Syntax:
class A{
{
//This is instance block of class A
}
}

0 comments:

Post a Comment