Академический Документы
Профессиональный Документы
Культура Документы
Method Overloading is the ability to define more than one method with the same
name in a class but with different parameters. The compiler is able to distinguish
between the methods because of their method signatures.
class Calculate{
obj.sum(10,20);
obj.sum(10,20,30);
Output:
class Calculate{
obj.sum(10,20);
Output:
class Calculate{
return a+b;
return a+b;
obj.sum(10,20);
Output:
compile time error is generated
Calculate.java:4: sum(int,int) is already defined in Calculate
double sum(int a, int b){
^
1 error
Can we overload main() method ?
Yes, it is possible to overload main() method with the help of method overloading.
Let's see an example below through which it will be clear that we can overload main()
method.
class MainDemo{
System.out.println("Duplicate main");
System.out.println("Original main");
main();
Output:
Original main
Duplicate main
Method Overloading and Type
Promotion
It must be clear from the above diagram that byte can be promoted to short, int, long,
float or double. The short datatype can be promoted to int,long,float or double. The
char datatype can be promoted to int,long,float or double and so on.
One type is promoted to its greater type implicitlty it no matching datatype is
found.
class TypePromotion{
System.out.println(a+b+" long");
Output:
42 long
In the above example integer value is passed through obj.add(21,21) which will be
implicitly promoted to its nearest bigger type i.e. long type.
class TypePromotion{
System.out.println(a+b+" float");
Output:
42.0 float
In the above example integer value is passed through obj.add(21,21) which will be
implicitly promoted to its nearest bigger type i.e. float type. [note:nearest bigger type
of int is long which is not matched in the above program, therefore next bigger type is
matched and is promoted to float implicitly]
class TypePromotion{
}
public static void main(String args[]){
obj.add(21,21);