Java Lesson 7-2
Java Lesson 7-2
Methods and
Constructors
Dr. Ei Ei Moe
Lecturer
©https://blogs.ashrithgn.com/
Objective
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.
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)
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;
}
Different number of
Rule 1 public Person ( ) { ... } parameters
public Person (int age) { ... }
public Fraction( ){
setNumerator(0); Creates 0/1
setDenominator(1);
}
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());
}
NEXT Topic
• Call-by-Value Parameter Passing