In this program, we will create a class that contains an Instance Initializer Block, which is used to initialize Instance data members.
Program/Source Code:
The source code to initialize Instance Data Member using Instance Initializer Block is given below. The given program is compiled and executed successfully.
// Java program to initialize Instance Data Member
// using Instance Initializer Block
class Sample {
int num;
//Instance Initializer Block
{
num = 200;
}
//Constructor
Sample() {
System.out.println("Num is: " + num);
}
}
public class Main {
public static void main(String[] args) {
Sample S = new Sample();
}
}
Output:
Num is: 200
Explanation:
In the above program, we created two classes Sample and Main. The Sample class contains an instance member num, and Instance Initializer Block to initialize data members. It also contains a constructor.
In this program, we will create a class that contains an Instance Initializer Block, which is used to initialize Instance data members.
Program/Source Code:
The source code to initialize Instance Data Member using Instance Initializer Block is given below. The given program is compiled and executed successfully.
Output:
Explanation:
In the above program, we created two classes Sample and Main. The Sample class contains an instance member num, and Instance Initializer Block to initialize data members. It also contains a constructor.