Q:

Java program to initialize instance data member using instance initializer block

0

Java program to initialize instance data member using instance initializer block

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java program to implement instance initializer blo... >>
<< Java program to call an Instance Initializer Block...