Method Overloading



Method Overloading in Java
When two or more methods having same name but different parameters or types is known as Method Overloading. Method overloading increases the readability of the program. Method Overloadingis also known as Static Polymorphism.
Different ways of overloading the method
Ans. There are two ways of method overloading in java.
1) By changing number of arguments or parameters
2) By changing the data type (int, float, double)
Simple Example of Method Overloading with different parameters: -

Example1: -
class demo
{
          void display()
          {       
                   System.out.println("Hello Safal");
          }
          void display(int a)
          {       
                   System.out.println(a);
          }
}
class funover       //save the by funover.java
{
public static void main(String args[])
          {
                   demo s = new demo();
                   s.display();
                   s.display(5);
          }
}
OUTPUT:-
Hello Safal
5

Example2: -
class para
{ 
void sa(int a,int b)
          {
                   System.out.println(a+b);
          } 
void sa(int a,int b,int c)
          {
                   System.out.println(a+b+c);
          } 
public static void main(String args[])
          { 
                   para obj=new para(); 
                   obj.sa(6,6); 
                   obj.sa(5,5,5); 
} 
}
OUTPUT:-
12
15
Can we overload main() method?
Yes, by method overloading. You can have any number of main methods in a class by method overloading.
Example3: -
class over
{ 
public static void main(int a)
          { 
                   System.out.println(a); 
          } 
public static void main(String args[])
          { 
                   System.out.println("main() method invoked");
                   over s = new over();
                   s.main(1); 
          } 
} 
Output: -
main() method invoked
1


Simple Example of Method Overloading By changing the data type this topic i will discuss after three days. You like my post Please share with friends


 

No comments:

Post a Comment