Java Reference
In-Depth Information
thispurposeisagoodideabecauseitletsyouinitializetheinstancefieldatconstruction
time and also at a later time. (Perhaps the employee changes his or her name.)
Note When you invoke a class's instance or class method from a constructor or
method within the same class, you specify only the method's name. You don't prefix
themethodinvocationwiththememberaccessoperatorandanobjectreferenceorclass
name.
setName() uses an if statement to detect an attempt to assign a null reference to
the name field.Whensuchanattemptisdetected,itoutputsthe“ name cannot be
null ” error message and returns prematurely from the method so that the null value
cannot be assigned (and replace a previously assigned name).
Caution Whenusingthereturnstatement,youmightrunintoasituationwherethe
compilerreportsan“unreachablecode”errormessage.Itdoessowhenitdetectscode
that will never be executed and occupies memory unnecessarily. One area where you
mightencounterthisproblemistheswitchstatement.Forexample,supposeyouspeci-
fy case "-v": printUsageInstructions(); return; break; aspart
ofthisstatement.Thecompilerreportsanerrorwhenitdetectsthebreakstatementfol-
lowingthereturnstatementbecausethebreakstatementisunreachable;itnevercanbe
executed.
Thepreviousformofthereturnstatementisnotlegalinamethodthatreturnsavalue.
Forsuchmethods,Javaprovidesanalternate versionofreturnthatletsthemethodre-
turnavalue(whosetypemustmatchthemethod'sreturntype).Thefollowingexample
demonstrates this version:
double divide(double dividend, double divisor)
{
if (divisor == 0.0)
{
System.out.println("cannot divide by zero");
return 0.0;
}
return dividend/divisor;
}
divide() uses an if statement to detect an attempt to divide its first argument by
0.0,andoutputsanerrormessagewhenthisattemptisdetected.Furthermore,itreturns
0.0 tosignifythisattempt.Ifthereisnoproblem,thedivisionisperformedandtheres-
ult is returned.
Search WWH ::




Custom Search