2011-12-11

What is method overriding in java ?

Redefining super class method in sub class is called method overriding. Method overriding, in object oriented programming, is a language feature that allows a sub class to provide a specific implementation of a method that is already provided by one of its super classes. The implementation in the sub class overrides (replaces) the implementation in the super class. If a method in sub class contains signature same as super class non private method, sub class method is treated as overriding method and super class method is treated as overridden method.

//Example.java
class Example  
{  
   void add(int a,int b){
      System.out.println("Example add:"+(a+b));
   }
   void sub(int a,int b){
      System.out.println("Example sub:"+(a-b));
   }
}   

//Sample.java
class Sample extends Example  
{       
   void add(int a,int b){
      System.out.println("Sample add:"+(a+b));
   }
   public static void main(String[] args)  
   {  
      Sample s = new Sample();
   s.add(10,20);
   s.sub(10,20);
   }  
}  

In the above program, add(int,int) method in Sample overrides add(int, int) in Example,because both methods have same signature and it is not private in Example class. Then Example class add() method is called overridden method, Sample class add() method is called overriding method. Here Sample class add() method is executed because add method is called from Sample class main method so first preference is given to Sample class add() method and it is executed. Here signature means add(int,int).

Loading

Enter your Email here: