OOAD Princhiples Q/A #7


Question:What is method overriding? When does it occur? Explain with examples.

Answer:

Method overriding refers to have a different implementation of the same method in the derived class. One of such method would exist in the base class and another in the derived class. These two methods have the same signature, but have different implementation. This means that the derived class method has the same name and parameter list as the base class overridden method. Method overriding is a feature to allow a subclass to provide a specific implementation of a method that is already been provided by one of its super classes. The implementation in the sub class overrides the implementation in the super class. Method overriding is an important feature that facilitates polymorphism in the design of the object oriented programs.

Foe example, class Circle have method called area( ) which calculates the area of circle. The sub class cylinder to class circle may have same method area( ) which calculates the area of cylinder. It is done by invoking method to find the area of cylinder. The following steps demonstrates this.

Step 1

Define a class circle.

class circle 
{
   // declaring the instance variable
   protected double radius;
   public circle (double radius )
   {
       this.radius = radius;
   }
   public double area ( )
   {
      return (3.14* radius* radius);
   }
};

Step 2

The next step is to define a sub class which can override the area( ) method in the circle class. The derived class will be the cylinder class. The area( ) method in the circle class computes the area of a circle, while the area( ) 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 variable
   protected double height;
   public cylinder (double radius , double height )
   {
      super (radius );
      this.height = height;
   }
   public double area( )
   {
      // method overridden here 
      return (2 * super.get area ( ) +2 *3.14*radius * height );
   }
};

When the overridden method area() is invoked for an object of the cylinder class, the new definition of the method is called and not the old definition from the super class circle.

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements