Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Beginner
Feb 3, 2000

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); 
} 
Behrouz Fallahi
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date