Showing posts with label Java method overloading. Show all posts
Showing posts with label Java method overloading. Show all posts

Thursday 26 August 2021

Java program for method overloading

 In Java, it is possible to define two or more methods with the same name but their functionality will differ based on the number of arguments and type of arguments. 

Method overloading implements one of the important object oriented programming concept called polymorphism. Poly means many. Morph means taking different forms. Here in method overloading methods with same name are defined to carry out different task.

Whenever an overloaded method is invoked, they are identified by the type and number of arguments. The overloaded methods may also differ by the return type.


PROGRAM

import java.io.*;
class Method_Overload
{
       int sum(int x,int y)
       {  
           return x+y;
       }
       float sum(int x, float a)
        {
           return x+a;
        }
        int sum(int z,char c)
        {
              return z+c;
        }
       public static void main(String args[]) throws IOException
       {
             int x,y,z;
             float a,b;
             char c;
             Method_Overload m=new Method_Overload();
             BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); 
             System.out.println("Enter x and y");
             x=Integer.parseInt(in.readLine());
             y=Integer.parseInt(in.readLine());
             System.out.println("Sum(x,y) = "+m.sum(x,y));
             System.out.println("Enter a value");
             a=Float.parseFloat(in.readLine());
             System.out.println("Sum(x,a) = "+m.sum(x,a));
             System.out.println("Enter a character");
             z=in.read();
             System.out.println("Sum(z,c) = "+m.sum(x,z));
          }
}

  

OUTPUT

E:\Java\Programs>javac Method_Overload.java


E:\Java\Programs>java Method_Overload

Enter x and y

5

10

Sum(x,y) = 15

Enter a value

4.5

Sum(x,a) = 9.5

Enter a character

B

Sum(z,c) = 71