Method Overloading in Java
When a method have same name but their no. of arguments and type of arguments is different in a class is called method overloading. Here is an example
1. No. of Arguments
public class MethodOverloadingDemo
{
void multiplication(int x,int y)
{
System.out.println("x*y : "+(x*y));
}
void multiplication(int x,int y,int z)
{
System.out.println("x*y*z : "+(x*y*z));
}
public static void main(String[] args)
{
MethodOverloadingDemo myObject = new MethodOverloadingDemo();
myObject.multiplication(10,12); // print x*y : 120
myObject.multiplication(10,12,15); // print x*y*z : 1800
}
}
2. Type of Arguments
public class MethodOverloadingDemo
{
void substact(int x,int y)
{
System.out.println("x-y : "+(x-y));
}
void substact(double x,double y)
{
System.out.println("x-y : "+(x-y));
}
public static void main(String[] args)
{
MethodOverloadingDemo myObject = new MethodOverloadingDemo();
myObject.substact(15,12); // print x-y : 3
myObject.substact(20.0,12.5); // print x-y : 7.5
}
}
Find us :
Facebook : @apnaandroid
Google+ : Apna Java
YouTube : Android & Java Tutorial
1. No. of Arguments
public class MethodOverloadingDemo
{
void multiplication(int x,int y)
{
System.out.println("x*y : "+(x*y));
}
void multiplication(int x,int y,int z)
{
System.out.println("x*y*z : "+(x*y*z));
}
public static void main(String[] args)
{
MethodOverloadingDemo myObject = new MethodOverloadingDemo();
myObject.multiplication(10,12); // print x*y : 120
myObject.multiplication(10,12,15); // print x*y*z : 1800
}
}
2. Type of Arguments
public class MethodOverloadingDemo
{
void substact(int x,int y)
{
System.out.println("x-y : "+(x-y));
}
void substact(double x,double y)
{
System.out.println("x-y : "+(x-y));
}
public static void main(String[] args)
{
MethodOverloadingDemo myObject = new MethodOverloadingDemo();
myObject.substact(15,12); // print x-y : 3
myObject.substact(20.0,12.5); // print x-y : 7.5
}
}
Find us :
Facebook : @apnaandroid
Google+ : Apna Java
YouTube : Android & Java Tutorial
Comments
Post a Comment