Java Programming : Overloaded
Methods and
Constructors
Dr. Ei Ei Moe
Lecturer
©https://blogs.ashrithgn.com/
Objective
• To understand how to work overloaded methods and constructors
Faculty of Computer Science
Overloaded Methods
1 Methods of the same name can be declared in the same class,
as long as they have different sets of parameters is called
method overloading.
01 2
When an overloaded method is called, the Java compiler selects
the appropriate method by examining the number, types and
order of the arguments in the call.
Faculty of Computer Science
Overloaded Methods
public void myMethod (int x, int y) { ... } Different number of
Rule 1 parameters
public void myMethod (int x) { ... }
Rule 2 public void myMethod (double x) { ... }
Different data types
public void myMethod (int x) { ... }
Faculty of Computer Science
Overloaded Methods
int sum(int num1, int num2)
int sum(int num1, int num2, int num3)
double sum(double num1, double num2)
double sum(int num1, double num2)
double sum( double num2, int num1)
Faculty of Computer Science
Three Ways to Overloaded a Method
Number of parameters
add (int, int)
add (int, int, int) Data type of parameters
add (int, int)
Sequence of Data type of parameters
add (int, float)
add (int, float)
add (float, int)
Faculty of Computer Science
Overloaded Example
class Overload{
int r;
String s;
public static void main (String[] args){
public void setValue (int r, String s) {
Overload o = new Overload();
this.r = r;
o.setValue(10, “ok”);
this.s = s;
o.setValue(“ok”, 20);
}
}
public void setValue (String s, int r) {
}
this.r =r;
this.s =s;
}
Faculty of Computer Science
Overloaded Constructor
• Define more than one constructor to a class
Different number of
Rule 1 public Person ( ) { ... } parameters
public Person (int age) { ... }
Rule 2 public Pet (int age) { ... }
Different data types
public Pet (String name) { ... }
Faculty of Computer Science
Overloaded Constructor
public Fraction( ){
setNumerator(0); Creates 0/1
setDenominator(1);
}
public Fraction(int number){
setNumerator(number);
Creates number/1
setDenominator(1);
}
Faculty of Computer Science
Constructor and this
public Fraction ( ) {
This constructor is called by
this(0, 1); the other three constructors
}
public Fraction (int number) { public Fraction (int num, int denom) {
this(number, 1); setNumerator(num);
} setDenominator(denom);
}
public Fraction (Fraction frac) {
this (frac.getNumerator(),
frac.getDenominator());
}
Faculty of Computer Science
Summary
• How to work overloaded methods and constructors
NEXT Topic
• Call-by-Value Parameter Passing
Faculty of Computer Science