Home »
Java Programs »
Java Class and Object Programs
Java program to call static block using the anonymous object
Learn how to call static block using the anonymous object in Java?
Submitted by Nidhi, on March 26, 2022
Problem statement
In this program, we will create a class with a static block and constructor. Then we will create an anonymous object then called static block and constructor.
In a Java Program, when an object gets created then the static block is called, then the constructor gets called.
Java program to call static block using the anonymous object
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.
Java Class and Object Programs »