2011-12-16

Need of method overriding in java ?

If a super class method logic is not fulfilling sub class business requirements, sub class should override that method with required business logic. Usually in super class, methods are defined with generic logic which is common for all sub classes.
For instance if we take Shape type of classes all Shape classes like Rectangle,Square,Circle etc...should have methods area() and perimeter(). Usually these methods are defined in super class Shape with generic logic but in sub classes Rectangle,Square,Circle etc...these methods must have logic based on their specific logic. Hence in Shape sub classes, these two methods must be overridden with sub class specific logic.
We can also override the predefined methods like toString(),equals(),Hashcode() methods of object class, so that we can use it in different functionality. Let us take an example program.

class Example 
{
   void m1()
   {
      System.out.println("Example m1");
   }
   void m2()
   {
      System.out.println("Example m2");
      m1();
   }
}

class Sample extends Example
{
   void m1()
   {
      System.out.println("Sample m1");
   }
   public static void main(String[] args) 
   {
      Sample s = new Sample();
      s.m1();
      s.m2();
   }
}

Output:
Sample m1
Example m2
Sample m1

In the above program m1() method is overridden in sub class i.e Sample class. Whenever m2() method is called through sample class object first JVM checks m2() method in Sample class it is not available so JVM goes to super class i.e Example class m2() method, the method is there in that class so JVM executes m2() method in Example class, In that method whenever the control comes to m1() method JVM executes m1() method in Sample class because compiler replaces m1() by this.m1() after compilation. In 'this' variable current object reference is stored which is nothing but the Sample class object is stored in 'this' variable so Sample class m1() method is executed.One thing we have to keep in mind that Compiler will check only type of the variable but JVM checks object stored in the reference variable

Loading

Enter your Email here: