Is it possible to override a Java method of one class in same?


When we have two classes where one extends another and if, these two classes have the same method including parameters and return type (say, sample) the method in the subclass overrides the method in the superclass.

i.e. Since it is an inheritance. If we instantiate the subclass a copy of superclass’s members is created in the subclass object and, thus both methods are available to the object of the subclass.

But if you call the method (sample), the sampling method of the subclass will be executed overriding the super class’s method.

Example

 Live Demo

class Super{
   public static void sample(){
      System.out.println("Method of the superclass");
   }
}
public class OverridingExample extends Super {
   public static void sample(){
      System.out.println("Method of the subclass");
   }  
   public static void main(String args[]){
      Super obj1 = (Super) new OverridingExample();
      OverridingExample obj2 = new OverridingExample();
      obj1.sample();
      obj2.sample();
   }
}

Output

Method of the superclass
Method of the subclass

Overriding methods in the same class

While overriding −

  • Both methods should be in two different classes and, these classes must be in an inheritance relation.

  • Both methods must have the same name, same parameters and, same return type else they both will be treated as different methods.

  • The method in the child class must not have higher access restrictions than the one in the superclass. If you try to do so it raises a compile-time exception.

  • If the super-class method throws certain exceptions, the method in the sub-class should throw the same exception or its subtype (can leave without throwing any exception).

Therefore, you cannot override two methods that exist in the same class, you can just overload them.

raja
Published on 10-Sep-2019 15:02:26
Advertisements