Abstract Class with Static Block in Java


Write a Java program to demonstrate an abstract class with a static block

  • In the Shape class, there's a static block that prints "Static block in abstract class". Static blocks are executed when the class is loaded into the memory, and they execute only once.
  • The Circle class extends Shape and provides an implementation for the draw() method, which prints "Drawing circle".
  • In the Main class, an instance of Circle is created, which triggers the execution of the static block in the Shape class. Then, the draw() method of the Circle instance is called, printing "Drawing circle" to the console.

Source Code

abstract class Shape
{
	static {
		System.out.println("Static block in abstract class");
	}
 
	abstract void draw();
}
 
class Circle extends Shape
{
	@Override
	void draw()
	{
		System.out.println("Drawing circle");
	}
}
 
public class Main
{
	public static void main(String[] args)
	{
		Circle circle = new Circle();
		circle.draw();
	}
}

Output

Static block in abstract class
Drawing circle