Can we change method signature in overriding in Java?

JavaObject Oriented ProgrammingProgramming

No, while overriding a method of the super class we need to make sure that both methods have same name, same parameters and, same return type else they both will be treated as different methods.

In short, if we change the signature, you cannot override the super class’s method if you try the method of the super class will be executed.

Reason − If you change the signature both are considered as different methods and, since the copy of super class method is available at sub class object, it will be executed.

Example

 Live Demo

class Super {
   void sample(int a, int b) {
      System.out.println("Method of the Super class");
   }
}
public class MethodOverriding extends Super {
   void sample(int a, float b) {
      System.out.println("Method of the Sub class");
   }
   public static void main(String args[]) {
      MethodOverriding obj = new MethodOverriding();
      obj.sample(20, 20);
   }
}

Output

Method of the Super class
raja
Published on 15-Oct-2019 07:02:24
Advertisements