Tuesday, 21 January 2014

METHOD OVERRIDING IN JAVA

Method Overriding

Brief note about method overriding 


Method overriding means have same signature but with different implementation. It occurs when a class declares a method that has the same type signature as a method declared by one of its super classes.Signature is a combination of a method name and the sequence of its parameter types.When a method in the subclass overrides a method in a super class, the method in the super class is hidden relative to the subclass object.Method Overriding is a very important feature of java because it forms the basis for run-time polymorphism.  

-> Rules of method overriding:


Argument list: The argument list of overriding method must be same as that of the method in parent class. The data types of the arguments and their sequence should be maintained as it is in the overriding method.
Return type: The return type of the overriding method (method of subclass) cannot be more restrictive than the same method of parent class.  For e.g. if the return type of base class method is public then the overridden method (child class method ) cannot have private, protected and default return type as these all three are more restrictive than public.For e.g. This is not allowed as child class disp method is more restrictive(protected) than base class(public).

-> Advantage of method overriding:


The main advantage of method overriding is that the classcan give its own specific implementation to a inherited method without even modifying the parent class(base class).

Syntax of Method Overriding:

class clsName1
{
     // methods
     rtype1 mthName(cparam1)
     {
             // body of method
     }
}

class clsName2 extends clsName1
{
     // methods
     rtype1 mthName(cparam1)
     {
             // body of method
     }
}

-> Super keyword in Overriding:


super keyword is used for calling the parent class method/constructor. super.methodname() calling the specified method of base class while super() calls the constructor of base class. Let’s see the use of super in Overriding.

class ABC
{
   public void mymethod()
   {
       System.out.println("Class ABC: mymethod()");
   }    
}
class Test extends ABC
{
   public void mymethod()
{
      //This will call the mymethod() of parent class
      super.mymethod();
      System.out.println("Class Test: mymethod()");
   }
   public static void main( String args[]) 
{
      Test obj = new Test();
      obj.mymethod();
   }
}

Output:
Class ABC: mymethod()
Class Test: mymethod()

No comments :

Post a Comment