Protected Variables in Abstract Class in Java


Create a Java program to demonstrate an abstract class with a protected variable

  • Shape is an abstract class with a protected member variable color and an abstract method draw().
  • The constructor of Shape initializes the color variable with the value passed as an argument.
  • Circle is a subclass of Shape and provides an implementation for the draw() method. It also has a constructor that initializes the color variable using the super() call to the constructor of the superclass.
  • In the Main class, an instance of Circle is created with the color "Red" and its draw() method is called. This method prints "Drawing circle of color : Red" to the console.

Source Code

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

Output

Drawing circle of color : Red