Java Lecture Sheet
Java Lecture Sheet
}
public void add(int i) {
}
}
PROGRAM FOR METHOD OVERLOADING
class Multiply { }
void mul(int a, int b) {
System.out.println("Sum of two=" + (a * b));
}
OUTPUT:
Sum of two=60
Sum of three=300
Why method overloading in java is not possible by
changing the return type of method is changed?
• In Java, method overloading is not possible by changing the return type of
the method because there may arise some ambiguity. Let's see how
ambiguity may occur:
}
}
class Main
{
public static void main (String args[])
{
DispOvrload o1 = new DispOvrload();
01.show('G');
01.show( 'S', 'J' );
}
}
Output:
class DispOvrload
}
public void show(char ch, int numb)
{
System.out.println ("The show method' is defined for the first time.");
}
public void show(int numb, char ch)
{
System.out.println ("The 'show method' is defined for the second time." );
}
}
class Main
{
public static void main (String args[])
{
DispOvrload o1 = new DispOvrload();
01.show('G', 62);
01.show(46, 'S');
}
}
Output:
The 'show method' is defined for the first time.
The 'show method' is defined for the second time.
ADVANTAGES
• It is used to perform a task efficiently with smartness in programming.
• It increases the readability of the program.
• The Method overloading allows methods that perform proximately related
functions to be accessed using a common name with slight variation in
argument number or types.
• They can also be implemented on constructors allowing different ways to
initialize objects of a class.
DISADVANTAGES
• Not very easy for the beginner to opt this programming technique and go
with it.
• It requires more significant effort spent on designing the architecture (i.e.,
the arguments' type and number) to up front, at least if programmers' want
to avoid massive code from rewriting.
THANK YOU