MainMenu

Home Java Overview Maven Tutorials

Sunday 15 January 2017

Method Overloading in Java with Example



For Video Tutorial : Move on Youtube Channel


Note : Select the playlist as per your need & move with number sequence


Method Overloading in java with example


Video Tutorial for this Atricle : CLICK HERE



When there is more than one method with same name & different parameter with in a class then it is known as Method overloading
Also these methods can be accessed by objects using appropriate parameter.

Example : Below code have many method with same name but different parameter & will be accessed by object.

public class TestCsc
{
public void sum(int x, int y)
{
System.out.println("1st method Sum is " + (x+y));
}
public void sum(int x, int y, int z)
{
System.out.println("2nd method Sum is " + (x+y+z));
}
public void sum(int x, double y)
{
System.out.println("3rd method Sum is " + (x+y));
}
public void sum(double x, int y)
{
System.out.println("4th method Sum is " + (x+y));
}
public static void main(String args[])
{
TestCsc object = new TestCsc();
object.sum(10, 20);
object.sum(10, 20, 30);
object.sum(10, 20.5);
object.sum(10.5, 10);
}
}

Output:
1st method Sum is 30
2nd method Sum is 60
3rd method Sum is 30.5
4th method Sum is 20.5



Example : Below code have two method with same name but different parameter & will be accessed by object.
package chandan_test1;
class Chandan2
{
public void sum(int a, int b)
{
System.out.println("Your sum is : " +(a+b));
}
public void sum(int a, int b, int c)
{
System.out.println("your sum is : "+(a+b+c));
}
}
public class Chandan1
{
public static void main(String args[])
{
Chandan2 obj = new Chandan2();
obj.sum(3,5);
obj.sum(4,6,8);
}
}
Output:
Your sum is : 8
your sum is : 18

Tags :Method overloading in java, what is method overloading in java?

No comments:

Post a Comment