Method Overloading

To achieve compile-time polymorphism we use method overloading :

There are some rules of method overloading

  • Methods  must present in the same class
  • Methos should have the same name
  • Methos should have different argument
    •  No of argument
    • Type of argument
    • Sequence of argument

See the example of the method overloading


the number of argument  not same :

public class TestDemo {
     public void show(String first,String last)  //diff. no of argument
    {
      System.out.println(first+last);
    }
    public void show(String name) // diff. no of argument
    {
      System.out.println( name);
    }

   public static void main(String[] args) {
     TestDemo  t = new TestDemo();
      t.show("rahul","singh");
      t.show("rahul");
   }
    
}

output

rahul
your score is 19 rahul singh

here in this example class TestDemo contain two method
this two method has

  • the same type of argument
  • but the number of argument different

first method show contains two string argument: String first, last;

first method show contains one string argument: String name;


Type of Argument different

public class TestDemo {
     public void show(String name)  //different type of argument
    {
      System.out.println(name);
    }

    public void show(int score) // different type of argument
    {
      System.out.println("your score is "+ score);
    }

   public static void main(String[] args) {
     TestDemo  t = new TestDemo();
      t.show("rahul singh");
      t.show(20);
   }
    
}

output

rahul singh
your score is 20

here in this example class TestDemo contain two method
this two method has:

  • the different type of argument
  • but the number of argument is the same

first method show contains two string argument: string score;

first method show contains one string argument: int name;


The sequence of argument:

Example

public class TestDemo {
     public void show(String name,int score)  //same argument but diff. series
    {
      System.out.println(name+score);
    }

    public void show(int score,String name) // same argument but diff. series
    {
      System.out.println(score + name);
    }


   public static void main(String[] args) {
     TestDemo  t = new TestDemo();
      t.show("rahul singh",25);
      t.show(20,"rahul singh");
   }
    
}

output

rahul singh25
20rahul singh
  • here in this example class TestDemo contain two method
    this two method has
    the same type of argument
  • the same number of argument
     but the position of argument different

first method show contains two string argument: string name, int score;

first method show contains one string argument: int score, string name;



SHARE THIS PAGE





Important Link