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.
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.
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);
}
}
Your sum is : 8
your sum is : 18
No comments:
Post a Comment