Java Reference
In-Depth Information
valuesuchaspi(3.14159…).Javaletsyouaccomplishthistaskbyprovidingreserved
word final .
Each object receives its own copy of a read-only instance field. This field must be
initialized,aspartofthefield'sdeclarationorintheclass'sconstructor.Ifinitializedin
the constructor, the read-only instance field is known as a blank final because it does
nothaveavalueuntiloneisassignedtoitintheconstructor.Becauseaconstructorcan
potentiallyassignadifferentvaluetoeachobject'sblankfinal,theseread-onlyvariables
are not truly constants.
Ifyouwantatrue constant ,whichisasingleread-onlyvaluethatisavailable toall
objects,youneedtocreatearead-onlyclassfield.Youcanaccomplishthistaskbyin-
cluding the reserved word static with final in that field's declaration.
Listing 2-8 shows you how to declare a read-only class field.
Listing 2-8. Declaring a true constant in the Employee class
class Employee
{
final static int RETIREMENT_AGE = 65;
}
Listing 2-8 ' s RETIREMENT_AGE declaration is an example of a compile-time con-
stant .Becausethereisonlyonecopyofitsvalue(thankstothe static keyword),and
because this value will never change (thanks to the final keyword), the compiler is
freetooptimizethecompiledcodebyinsertingtheconstantvalueintoallcalculations
whereitisused.Thecoderunsfasterbecauseitdoesn'thavetoaccessaread-onlyclass
field.
Reviewing Field-Access Rules
Thepreviousexamplesoffieldaccessmayseemconfusingbecauseyoucansometimes
specifythefield'snamedirectly,whereasyouneedtoprefixafieldnamewithanobject
reference or a class name and the member access operator at other times. The follow-
ingrulesdispelthisconfusionbygivingyouguidanceonhowtoaccessfieldsfromthe
various contexts:
• Specifythenameofaclassfieldasisfromanywherewithinthesameclassas
the class field declaration. Example: counter
 
Search WWH ::




Custom Search