Use Overloaded Methods To Simulated Optional Parameters

Some languages, like C++, let us declare optional parameters. For example, the following is a valid method signature in C++:

 public aMethod(int x, int y=0, int z=0); 

where parameters y and z are optional in the sense that if we call the method “aMethod” as in:

  aMethod(1,2,3); 

x is set to 1, y is set to 2, and z is set to 3. But if we call the method as in: x is set to 1, y is set to 2, and z is set to 0. and if we write

  aMethod(1) 

x is set to 1, y is set to 0, and z is set to 0.

Java does not support this feature. But if we need it, we can overload aMethod to obtain the same effect. We can write:

 public void aMethod(int x, int y, int z) {    ... } //now we overload the method aMethod to cover the cases that //aMethod is called with 1, or 2 parameters public void aMethod(int x, int y) {    //call aMethod and pass default value for z    aMethod(x, y, 0); } public void aMethod(int x) {    //call aMethod and pass default value for y and  z    aMethod(x, 0, 0); } 
Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: