Method overriding in java


Method overriding:

Method overriding means having the same method in parent class/super class and child class/sub class.
In a word, same method but different implementation.

Example:

Super class:

class Circle
{
protected double radius;
public Circle(double radius)
{
      this.radius = radius;
}
// other method definitions here
public double getArea()
{
      return Math.PI*radius*radius;
}
}// end of class circle

Sub class:

class Cylinder extends Circle
{
protected double length;
public Cylinder(double radius, double length)
{
     super(radius);
     this.length = length;
}


public double getArea()
{
     // method overriden here
     return 2*super.getArea()+2*Math.PI*radius*length;
}

}// end of class Cylinder