
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Change Method Signature in Overriding in Java
No, you cannot change the method signature while overriding. Changing the method signature becomes method overloading, not overriding. Now, let's understand why -
Method Signature
In Java, a method signature consists of -
-
Method name: It is used to call the method.
-
Parameter list: It includes the number, type, and order of parameters.
Note: The method signature does not include return type, access modifiers (public, private, protected), throws clause, static, final, and abstract keywords.
Changing the Method Signature in Overriding
Overriding refers to defining a method in a subclass with the same signature as a method in the superclass. While overriding a method of the super class, we need to make sure that both methods have the same name, same parameters, and same return type, else they both will be treated as different methods.
In short, if we change a method's signature in a subclass, we aren't overriding the superclass method but creating a new one. When this method is called through either a superclass reference, the superclass's method will be executed instead of the (new) subclass method.
The super class reference variable can hold the subclass object. But, with this, we can only access the members of the super class.
If you change the signature, both are considered as different methods, and since the copy of the super class method is available at the sub-class object, it will be executed.
Example
Following is an example -
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); } }
Let us compile and run the above program, this will give the following result ?
Method of the Super class