Tuesday, April 10, 2007

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).

1 comments :

Wasib Ali Khan on December 25, 2011 at 6:56 AM said...

Make a new Class name like OverriddenExp.

class OverriddenExp{

public static void main(String arg[]){

Circle circle=new Circle();
System.out.println("Area of Circle is"+circle.getArea());
// It show area of circle class

Cylinder cylinder=new Cylinder ();
System.out.println("Area of Cylinder is"+cylinder.getArea());
// It show area of Cylinder class

Circle obj=new Cylinder ();
System.out.println("Area of Cylinder is"+obj.getArea());
// It show area of Cylinder class because we make the ref of Circle class and object of Cylinder class.

 

Disclaimer
Interview Questions On Java,Java EE Copyright © 2016. Reads: best tracker