Q:

Java program to call static block using the anonymous object

belongs to collection: Java Class and Object Programs

0

Java program to call static block using the anonymous object

All Answers

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

Program/Source Code:

The source code to call the static block using an anonymous object is given below. The given program is compiled and executed successfully.

// Java program to call static block 
// using an anonymous object

class Sample {
  static {
    System.out.println("Static block called");
  }

  Sample() {
    System.out.println("Constructor called");
  }

}

public class Main {
  public static void main(String[] args) {
    new Sample();
  }
}

Output:

Static block called
Constructor called

Explanation:

In the above program, we created two classes Sample and Main. The Sample class contains a Static Block and a constructor.

The Main class contains a method main(). The main() method is the entry point for the program, here we created an anonymous object of the Sample class and called static block and constructor of the class.

 

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

total answers (1)

Java Class and Object Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to check whether a class is a local c... >>
<< Java program to represent the class in different w...