Method Overriding

Overriding is another useful feature of object-oriented programming technique.

Method Overriding

Overriding is another useful feature of object-oriented programming technique.

Method Overriding

Method Overriding

     

Overriding is another useful feature of object-oriented programming technique. It provide the facility to redefine the inherit method of the super class by a subclass. The method overriding is used to invoking the parent class method by a child class. It is possible when a child class extends the parent class then all the attributes and the methods of parent class inherit by child class. The methods name and the parameters pass in the subclass are same as superclass methods. The restriction of the access modifier of the subclass method should not more than the superclass method e.g. if the superclass method is protected, the overriding method may be protected or public.

Here is an example of the method overriding. Create a class "Override" and create two subclasses "One" and "Two" and define a same method in both of them. When the main class call the method the method executes on behalf of their definition. In the given example we are trying to illustrate the same technique.

Here is the Code of the Example :

"Override.java"

import java.lang.*;

class One {
  int first = 100;
  int func() { return first; }
  }
  class Two extends One {
  int first = 200;
  int func() { return -first; }
  }
  public class Override {
  public static void main(String args[]) {
  Two obj2 = new Two();
  System.out.println(obj2.first);
  System.out.println(obj2.func());
  One obj1 = (One) obj2;
  System.out.println(obj1.first);
  System.out.println(obj1.func());
  }
  }

Here is the Output of the Example :

C:\roseindia>javac Override.java

C:\roseindia>java Override
200
-200
100
-200

Download This Example :