Abstract Class with Variables & Methods in Java


Write a Java program to demonstrate an abstract class having variables and methods

  • The Shape class is declared as abstract with an instance variable color, a constructor to initialize this variable, an abstract method draw(), and a concrete method displayColor() to display the color of the shape.
  • The Circle class extends Shape and provides its own constructor to initialize the color inherited from Shape.
  • The Circle class overrides the abstract method draw() to provide its specific implementation.
  • In the main method, an instance of Circle is created with the color "Blue". Its displayColor() method is called to print the color, and its draw() method is called to draw the circle.

Source Code

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

Output

Shape color is : Blue
Drawing Circle