Subclass Method Adds New Parameter to Superclass Method In Java


Write a Java program to demonstrate method overriding with a subclass that overrides a method from a superclass and adds a new parameter to the method

Class hierarchy with a base class Shape and a subclass Circle. The Shape class has a method draw, and the Circle class has a method draw with an additional parameter int radius. Here's an explanation of the code:

  • Shape is a class with a method draw that prints "Drawing a shape" to the console.
  • Circle is a subclass of Shape. It has a method draw that has an additional parameter int radius. This method prints "Drawing a circle with radius [radius]" to the console, where [radius] is the value of the radius parameter.
  • In the Main class, you create an instance of the Circle class named circle and call the draw method on it, passing an int value of 5 as the radius parameter.

When you run the code, it will create a Circle object, and since the draw method in the Circle class takes an int parameter, it will call the version of the draw method in the Circle class that accepts the int parameter.

Source Code

class Shape
{
    void draw()
	{
        System.out.println("Drawing a shape");
    }
}
 
class Circle extends Shape
{
    void draw(int radius)
	{
        System.out.println("Drawing a circle with radius " + radius);
    }
}
 
public class Main
{
    public static void main(String[] args)
	{
        Circle circle = new Circle();
        circle.draw(5);
    }
}

Output

Drawing a circle with radius 5