Private Method in Abstract Class in Java


Create a Java program to demonstrate an abstract class with a private method

  • Shape is an abstract class with an abstract method draw() and a private method display(). The draw() method must be implemented by any concrete subclass, while the display() method is private and cannot be accessed by subclasses or external classes.
  • Shape also has a method process() which calls display() and draw(). Since process() is not final, it can be overridden by subclasses.
  • Circle extends Shape and provides an implementation for the draw() method, printing "Drawing circle" to the console.
  • The Main class creates an instance of Circle, calls its process() method, which in turn calls display() and draw(). Since display() is private, it cannot be accessed directly from the Main class, but it can be invoked within the process() method of the Shape class.

Source Code

abstract class Shape
{
	abstract void draw();
 
	private void display()
	{
		System.out.println("Displaying shape");
	}
 
	void process()
	{
		display();
		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.process();
	}
}

Output

Displaying shape
Drawing circle