Method overloading

Figure 239. Method overloading: Same name, different signature Slide presentation Create comment in forum
public class Print {
  public void print() {             // (void)
    System.out.println("No argument");
  }
  public void print(int i) {        // (int)
    System.out.println("int value " + i);
  }
  public void print(double d) {     // (double)
    System.out.println("double value " + d);
  }
  public void print(int i, int j) { // (int, int)
      System.out.println("Two int values "+
         i + " and " + j);
  }
}
Print p = new Print();
p.print();
p.print(33);
p.print(4.333);
p.print(-1, 7);
No argument
int value 33
double value 4.333
Two int values -1 and 7

Figure 240. Overloading, alternate names Slide presentation Create comment in forum
  • Static polymorphism.

  • Compile time binding.

  • Early binding.


Figure 241. No such concept in C Slide presentation Create comment in forum
void print() {
  printf("No argument\n");
}

void print(int i) {              /* Error: redefinition of ‘print’ */
  printf("int value %d\n", i);
}

void main(void) {
  print();
  print(33);
}

Figure 242. What about return type? Slide presentation Create comment in forum
public class Person {
  String getDetails() { return "dummy";}
  int getDetails() { return 1;} // Error: 'getDetails()' is already
                                // defined in 'Person'
}
Return type Method signature
Method name Argument type list
String getDetails (void)
int getDetails (void)

Return type irrelevant, only method signatures in Java.


Figure 243. Method signatures rationale Slide presentation Create comment in forum

In Java method signatures allow for uniquely addressing a method within a given class e.g.:

The method named print having an int argument followed by a double:

print(int, double)

Figure 244. Method signatures rationale Slide presentation Create comment in forum
Method signatures rationale