Two or functions or method with same name but different signature or header, can define within a class in Java. This programming concept is known as function overloading or method overloading.
Note: Signature can differ by the
- Change of the data types
- Numbers of the arguments
- Sequence of the arguments.
But if we change the data type from float to double or for it to short, long or byte, then function overloading is not executed properly due to type promotion of the data types.
Note: Method overloading is also known as Compile time binding or Early Binding.
import java.util.*;
public class JavaPower{
public int Power(int a){
return a*a;
}
public int Power(int a,int n){
int m=1;
for(int i=0;i<n;i++){
m=m*a;
}
return m;
}
public static void main(String []args){
int a,n;
Scanner sc=new Scanner(System.in);
System.out.print("Enter A Number : ");
a=sc.nextInt();
System.out.print("Enter A Power : ");
n=sc.nextInt();
JavaPower jp=new JavaPower();
System.out.println( a + " Square = " + jp.Power(a));
System.out.print(a + " To The Power = " + jp.Power(a,n));
}
}