Java OOPS  - Polymorphism - Part 1

Java OOPS - Polymorphism - Part 1

In this article, we will learn about Method Signature

Welcome to the 5th article of this series.
From this article onwards we will start understanding one of the important concepts in OOPS which is polymorphism.
We will learn what is overloading, overriding, static and dynamic binding.
But before that let us first learn about method signature because this term will be used many times and we should have a clear understanding of it.

Let us consider the below method and try to get its method signature.

public int m1(int a , float b){
        //do something

m1(int, float) is the method signature of the above method.
By this, we can say method signature in java consists of method name and datatypes of arguments in the exact order.
As of now, we know how to get the method signature of a method.
Now there might be a question that - What is the use of it? Who will make use of the method signature?
Java Compiler uses method signature while resolving method calls. Let us take an example and understand this.

public class Test {
    public void m1(int a){
    public  void m2(String name){

    public static void main(String[] args) {
        Test t = new Test();

The Test class has 2 methods m1 and m2.
So compiler maintains a method table that stores the method signature of all the methods.


So whenever we call t.m1(10) compiler checks

  1. t is of type Test
  2. In the Test method table, do we have any method with signature m1(int)? YES
  3. Executes successfully.

Now let's try to call a method whose signature is not in the method table.


Can you guess the output?
Yes, we will get a compile-time error.

java: cannot find symbol
  symbol:   method m3(double)
  location: variable t of type polymorphism.Test

I hope this is clear to all.
Now, if you have noticed in the method signature we don't have the return type in it.
Can we create 2 methods with the same signature and different return types?
Let's see.

public void m1(int a){
public int m1(int a){
        return a;
Compile Error - java: method m1(int) is already defined in class polymorphism.Test

We get a compile-time error in this case.

So that's it for this article if you have any suggestions please comment.
In the next article, we will start with the overloading concept.
Thanks for reading.