пятница, 5 января 2024 г.

Instance initializer block in Java

    An instance initializer block is a block of code within a class that is executed when an instance of the class is created. It is also known as an instance initialization block. The instance initializer block is defined without any keyword, and it is enclosed within curly braces '{}'.

public class Example {
private int x;

// Instance initializer block
{
System.out.println("Instance initializer block executed");
x = 10; // Common initialization code
}

// Constructor
public Example() {
System.out.println("Constructor executed");
}

// Getter method
public int getX() {
return x;
}

public static void main(String[] args) {
Example obj = new Example();
System.out.println("Value of x: " + obj.getX());
}
}

Instance initializer block executed
Constructor executed
Value of x: 10

The instance initializer block is executed in the order in which the classes are initialized, starting from the superclass to the subclass. The 'super' keyword can be used in the instance initializer block to explicitly call the superclass's instance initializer block or constructor.

class Superclass {
int superClassVariable;

// Superclass instance initializer block
{
System.out.println("Superclass Instance Initializer Block");
superClassVariable = 5;
}

// Superclass constructor
public Superclass() {
System.out.println("Superclass Constructor");
}
}

class Subclass extends Superclass {
int subclassVariable;

// Subclass instance initializer block
{
System.out.println("Subclass Instance Initializer Block");
subclassVariable = 10;
}

// Subclass constructor
public Subclass() {
super(); // This implicitly calls the superclass constructor
System.out.println("Subclass Constructor");
}
}

public class Example {
public static void main(String[] args) {
Subclass obj = new Subclass();
System.out.println("Superclass Variable: " + obj.superClassVariable);
System.out.println("Subclass Variable: " + obj.subclassVariable);
}
}


Superclass Instance Initializer Block
Superclass Constructor
Subclass Instance Initializer Block
Subclass Constructor
Superclass Variable: 5
Subclass Variable: 10

Комментариев нет:

Отправить комментарий