Can we have a class with two methods of same name?
Yes, with different method signatures
return_type method_name(type1, type2,…..)
Example
public int sum (int i, int j) has signature int sum (int,int)
public double sum(double i, double j) has signature double sum (double, double)
public double sum(int i, double j) has signature double sum (int, double)
The order matters in parameter list.
Example of method overloading
class MethodAdd{
public int add(int i, int j) {
return i+j;
}
public double add(double i, double j) {
return i+j;
}
}
class Test{
public static void main(String args [ ] ) {
MethodAdd o= new MethodAdd( ) ;
int a=10,b=20;
int result = o.add(a,b);
System.out.println(“sum of a and b is:” + result);
}
}
Rules for overloading
overloaded methods must differ in argument list.
number of arguments ( OR)
data types of arguments (OR)
sequence of data type of arguments
but may or may not have
changes in return type
changes the access modifier
declared new or broader checked exception
valid/invalid method overloading
Ex 1
int add( int a , int b)
int add (float a, float b)
Ex 2
int add (int a)
int add( int a, int b)
Ex 3
int add (int a, int b)
double add (int a, int b)
Негізгі бет Java 19 | Method Overloading in java
Пікірлер