I came across some Java code that had the following structure:
public MyParameterizedFunction(String param1, int param2)
{
this(param1, param2, false);
}
This is how I did it ... it's not as convenient perhaps as having an 'optional argument' against your defined parameter, but it gets the job done:
public void postUserMessage(String s,boolean wipeClean)
{
if(wipeClean)
{
userInformation.setText(s + "\n");
}
else
{
postUserMessage(s);
}
}
public void postUserMessage(String s)
{
userInformation.appendText(s + "\n");
}
Notice I can invoke the same method name with either just a string or I can invoke it with a string and a boolean value. In this case, setting wipeClean to true will replace all of the text in my TextArea with the provided string. Setting wipeClean to false or leaving it out all together simply appends the provided text to the TextArea.
Also notice I am not repeating code in the two methods, I am merely adding the functionality of being able to reset the TextArea by creating a new method with the same name only with the added boolean.
I actually think this is a little cleaner than if Java provided an 'optional argument' for our parameters since we would need to then code for default values etc. In this example, I don't need to worry about any of that. Yes, I have added yet another method to my class, but it's easier to read in the long run in my humble opinion.