In other words, why would you need an instance initializer? What difference or advantage do you have in writing a instance initializer over a constructor?
In other words, why would you need an instance initializer? What difference or advantage do you have in writing a instance initializer over a constructor?
At the time of object creation, if we want to perform initialise of instance variables, then we should go for Constructor, other than initialisation activity if we want to perform any activity at the time of object creation then we should go for instance block.
We can't replace constructor with instance block because constructor can take argument but instance block can't take arguments.
We can't replace instance block wih constructor because a class can contain more than one constructor. If we want to replace instance block with constructor then in every constructor we have to write instance block code because at runtime which constructor will be called we can't expect, this will unnecesarily increase duplicate code.
Example :
class MyClass{
static int object_count = 0;
MyClass(){
object_count++;
}
MyClass(int i){
object_count++;
}
void getCount() {
System.out.println(object_count);
}
public static void main(String... args) {
MyClass one = new MyClass();
MyClass two = new MyClass(2);
two.getCount();
}
}
Output : 2
class MyClass{
static int object_count = 0;
{
object_count++;
}
MyClass(){
}
MyClass(int i){
}
void getCount() {
System.out.println(object_count);
}
public static void main(String... args) {
MyClass one = new MyClass();
MyClass two = new MyClass(2);
two.getCount();
}
}
Output : 2