Method Overloading
Method Overloading
Method Overloading is a feature that allows a class to have more than one
method having the same name, if their argument lists are different.
syntax:
void func() { ... }
void func(int a) { ... }
float func(double a) { ... }
float func(int a, float b) { ... }
Here, the func() method is overloaded.
Simple Example :
Import java.util.Scanner;
class A
{
void disp(char c)
{
System.out.println(c);
}
void disp(char c, int num)
{
System.out.println(c + " "+num);
}
}
class Main
{
public static void main(String args[])
{
A a1 = new A();
a1.disp('a');
a1.disp('a',10);
}
}
OUTPUT :
a
a 10
METHODS OF OVERLOADING :
Output:
Arg : 1
Arg : 1 4
Java program to find the sum of two integer number and two float numbers by getting inputs from the
user using method overloading.
import java.util.Scanner;
class Add
int c;
float s;
c=x+y;
s=q+r;
System.out.println("the sum of two float integers"+s);
int a,b;
float a1,b1;
a=s.nextInt();
b=s.nextInt();
a1=s.nextFloat();
b1=s.nextFloat();
p.sum(a,b);
p.sum(a1,b1);
}
Program to find the power of a number.Use method overloading.First method have two integer
argument and second method have one integer argument and one double argument.
class Power
{
static int pow(int n,int m)
{
int i;
for(i=1;i<m;i++)
{
n=n*n;
}
return n;
}
void pow(double n,int m)
{
int i;
for(i=1;i<m;i++)
{
n=n*n;
}
System.out.println(n);
}
}
class Main
{
public static void main (String[] args) {
Power p=new Power();
System.out.println(Power.pow(4,2));
p.pow(11.1,2);
}
}