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

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


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

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


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
×
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.
Thanks for your registration, follow us on our social networks to keep up-to-date