Static Variables & Methods in Abstract Classes in Java


Write a Java program to demonstrate an abstract class with a static variable and method

  • The Shape class is declared as abstract with a static integer variable count and an abstract method draw().
  • The incrementCount() method is also declared as static, which increments the value of count.
  • The Circle class extends Shape and provides its implementation of the draw() method.
  • In the main method, an instance of Circle is created, and its draw() method is called, which prints "Drawing Circle".
  • Then, the static method incrementCount() of the Shape class is invoked to increment the count variable, and the total count of shapes is printed. In this case, it prints "Total shapes : 1" because one shape (a circle) has been drawn.

Source Code

abstract class Shape
{
	static int count = 0;
 
	abstract void draw();
 
	static void incrementCount()
	{
		count++;
	}
}
 
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();
		Shape.incrementCount();
		System.out.println("Total shapes : " + Shape.count);
	}
}

Output

Drawing Circle
Total shapes : 1