Method overloading in Java

METHOD OVERLOADING IN JAVA:
Method Overloading is a technique, in which a Java class can contain two or more methods with the same name but differed in signature (parameters).

For example,
void sum (int a, int b); having two parameters is different from,
void sum (int a, int b, int c); having three parameters.

3 ways of method overloading in Java:
1.    Number of parameters
2.   Data types of parameters
3.   Sequence of data types of parameters
1.    Number of parameters:
For example,
void sum (int a, int b);
void sum (int a, int b, int c);
2.   Data types of parameters:
For example,
void sum (int a, int b);
void sum (int a, float b);
3.   Sequence of data types of parameters:
For example,
void sum (int a, float b);
void sum (float a, int b);
Methods having same name, same parameters different return types are not a method overloading, it will through a compilation error.

This is invalid case of method overloading, shown below

int sum (int a, int b);
float sum (int a, int b);

Examples of all above 3 ways for method overloading:

1.Number of parameters
class ContainMethods
{
void display(char gender)
{
     System.out.println("gender= "+gender);
}
void display(char gender, int age)
{
     System.out.println("Gender=" +gender + ",Age= "+age);
}
}
public class MethodOverloading {
        public static void main(String args[])
          {
                    ContainMethods obj = new ContainMethods();
           obj.display('m');
           obj.display('m',60);
          }
}
OUTPUT:
gender= m
Gender=m,Age= 60

2. Data types of parameters.
class ContainMethods
{
void display(char a)
{
     System.out.println(a);
}
void display(int a)
{
     System.out.println(+a);
}
}
public class MethodOverloading {
        public static void main(String args[])
          {
                    ContainMethods obj = new ContainMethods();
           obj.display('m');
           obj.display(60);
          }
}
OUTPUT:
m
60

3.Sequence of datatypes of parameters
class ContainsMethods
{
void display(char gender, int age)
{
           System.out.println("gender= "+gender+",Age= "+age);
}
void display(int age, char gender)
{
     System.out.println("Age=" +age + ",Gender= "+gender);
}
}
public class MethodOverloading {
        public static void main(String args[])
          {
                    ContainsMethods obj = new ContainsMethods();
           obj.display('m',60);
           obj.display(60,'m');
          }
}
OUTPUT:
gender= m,Age= 60

Age=60,Gender= m

LEAVE A REPLY










Related topics

Please use contact page in this website if you find anything incorrect or you want to share more information about the topic discussed above.