Java Instance Initializer Block
In Java, an Instance Initializer Block is a block of code that is used to initialize instance variables. The Java Instance Initializer Block is executed before the constructors of the class.
Syntax
class MyClass {
{
// code to initialize instance variables
}
// Constructors and methods
}
Note: The Instance Initializer Block is enclosed in a pair of curly braces and is executed whenever an object of the class is created.
Example
public class Person {
private String firstName;
private String lastName;
private int age;
{
firstName = "John";
lastName = "Doe";
age = 25;
}
public Person() {
System.out.println("Constructor is called");
}
// getters and setters
}
Explanation
In the above example, we have defined an Instance Initializer Block inside the Person
class. The block initializes the firstName
, lastName
, and age
variables.
When an object of the Person
class is created, the Instance Initializer Block is executed before calling the constructor. In this case, we have defined a default constructor that prints a message on the console.
Use
Java Instance Initializer Block is used to initialize the instance variables of a class. It is executed before the constructors of the class, which makes it an excellent place to put the code that initializes instance variables. This block is also useful when the initialization code requires some logic that cannot be done in the constructors.
Important Points
- The Instance Initializer Block is executed whenever an object of the class is created.
- The Instance Initializer Block is executed before the constructors of the class.
- The Instance Initializer Block is useful when the initialization code requires some logic that cannot be done in the constructors.
Summary
In Java, an Instance Initializer Block is a block of code that is used to initialize instance variables. It is executed before the constructors of the class. The Instance Initializer Block is useful when the initialization code requires some logic that cannot be done in the constructors. It is an excellent place to put the code that initializes instance variables.