Access Modifiers in Abstract Classes in Java


Create a Java program to demonstrate the use of an abstract class and method with access modifiers

  • The Shape class is an abstract class with an abstract method draw(), which is marked as protected. This means that it can only be accessed within the same package or by subclasses.
  • The Circle class extends Shape and provides an implementation for the draw() method. Since it overrides a protected method, it must also be marked as protected or less restrictive.
  • In the Main class, an instance of Circle is created and its draw() method is called, which prints "Drawing circle" to the console.

Source Code

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

Output

Drawing circle