Aqua Phoenix
     >>  Lectures >>  Java 2  
 

Navigator
   
 
       
   

2.4 Overloading

UNDER CONSTRUCTION: THIS SECTION IS NOT YET COMPLETE

Method overloading is the process of creating several methods with the same name, but with different method signatures. Then, depending on what parameters the method is called with, the appropriately signed method is called.

signature = method name + all parameter types

void myMethod(int j, float k)

signature: myMethod(int, float)

different number of params, different order of params, different type of params

NOT VALID: if methods only different by return type (compile error!)

Example 1:

class Overload {
int r;
String s;

public void setValue(int a, String b){
  r = a;
  s = b;
}

public void setValue(String a, int b) {
  r = b;
  s = a;
}

public static void main(String[] args) {
  Overload o = new Overload();
  o.setValue(1, "One");  //this is fine
  o.setValue("One", 1); //this is fine too!
}
}
Example 2:

class Overload {
int r;
String s;

public void setValue(int r, String s){
  this.r = r;
  this.s = s;
}
public void setValue(String s, int r) {
  this.setValue(r, s);
}

public static void main(String[] args) {
  Overload o = new Overload();
  o.setValue(1, "One");  //this is fine
  o.setValue("One", 1); //this is fine too!
}
}

2.4.1 Keyword this

A reference to the current object!

Can be used only inside a method

Useful when referring to a member variable in class with same name as variable in method.

class ThisExample {
int r;
void setValue(int r){
  this.r = r;
}
ThisExample incrementR() {
  r++;
  return this;
}

public static void main(String[] args) {
  ThisExample x = new ThisExample();
  x.setValue(10);
  x.incrementR().incrementR();  //r is now 12
}
}
Can invoke one constructor from another

this(param) Useful if constructors share significant amount of initialization

Note: this() must be the first statement of the constructor!

Can be called only once!