Header Ads

  • Breaking Now

    What is method overriding?

    The method with same signature but with changed implementation lead to method overriding and that can occur in a parent child relation of classes. A method defined in parent class can be overridden in its child class with different implementation from its base class.

    An example:

    We will define a base class called Circle

    class Circle
    {
    //declaring the instance variableprotected double radius;
    public Circle(double radius)
    {
    this.radius = radius;
    }
    // other method definitions here
    public double getArea()
    {
    return Math.PI*radius*radius;
    }
    //this method returns the area of the circle

    }// end of class circle

    When the getArea method is invoked from an instance of the Circle class, the method returns the area of the circle.

    The next step is to define a subclass to override the getArea() method in the Circle class. The derived class will be the Cylinder class. The getArea() method in the Circle class computes the area of a circle, while the getArea method in the Cylinder class computes the surface area of a cylinder.
    The Cylinder class is defined below.

    class Cylinder extends Circle
    {
    //declaring the instance variableprotected double length;
    public Cylinder(double radius, double length)
    {
    super(radius);this.length = length;
    }
    // other method definitions herepublic
    double getArea()
    {
    // method overriden here
    return 2*super.getArea()+2*Math.PI*radius*length;
    }//this method returns the cylinder surface area

    }// end of class Cylinder

    When the overriden method (getArea) is invoked for an object of the Cylinder class, the new definition of the method is called and not the old definition from the superclass(Circle).

    Post Top Ad

    Post Bottom Ad