Method Overloading in java

METHOD OVERLOADING

  •  In a class defining multiple method with a same name and different parameter is
    known as method overloading.
  •  Parameter should differ either in terms of parameter type or
    parameter length.
  •  In a class we can overload both static and non-static method.
  • The overloaded method is invoked based on the argument.
  •  Any two method having same name should not be match of in terms of argument.
  •  Method overloading is used to achieve compile time polymorphism.

When to use method overloading:

  •  When developing application if we come across an operation which has to done to the different  parameter than we go for method overloading
  • i.e. while doing payment in Amazon website we have many payment option like debit  card, credit card and   wallet option to make payment but operation is same.
Method overloading Example

class Demo1
{

  	void test()
	
	{
		
		System.out.println("running no arg test method");
	}
	
	void test(int arg)
	{
		
		System.out.println("running int arg test method");
		
	}
    
	static void test(double arg1)//static method
	{
		
		System.out.println("running double arg static test method");
	}
	
	
}


public class MethodOverloading
{
	public static void main(String[] args) {
		
		System.out.println("*************************");
		
		Demo1 obj1=new Demo1();
		
		obj1.test();//calling no arg test method
		
		obj1.test(10);// calling int arg test method
		
		System.out.println("*************************");
		
		Demo1.test(12.4);//calling static test double arg method
		
		
		System.out.println("**************************");
					
	}
}


output:

*************************
running no arg test method
running int arg test method
*************************
running double arg static test method
**************************

Leave a Reply