Java Reference
In-Depth Information
ideaistocomparetheargumentobjectwiththecurrentobjecttodetermineiftheyare
equal.
Theequalitydeterminationismadebyusingthe == operatortocomparethevalueof
theargumentobject's x instance fieldwiththevalueofthecurrentobject's x instance
field, returning Boolean true when they are the same. What may seem baffling is that
Java lets you specify pa.x to access the argument object's private instance field.
Also, main() is able to directly access x , via the pa2 object.
I previously presented Java's four access-control levels and presented the following
statement regarding the private access-control level: “A field, method, or constructor
thatisdeclared private cannotbeaccessedfrombeyondtheclassinwhichitisde-
clared.”Whenyoucarefullyconsiderthisstatementandexamine Listing2-15 , youwill
realizethat x isnotbeingaccessedfrombeyondthe PrivateAccess classinwhich
it is declared. Therefore, the private access-control level is not being violated.
Theonlycodethatcanaccessthis private instancefieldiscodelocatedwithinthe
PrivateAccess class.Ifyouattemptedtoaccess x viaa PrivateAccess object
that was created in the context of another class, the compiler would report an error.
Beingabletodirectlyaccess x fromwithin PrivateAccess isaperformanceen-
hancement;itisfastertodirectlyaccessthisimplementationdetailthantocallamethod
that returns its value.
Compile PrivateAccess.java ( javac PrivateAccess.java ) and run
the application ( java PrivateAccess ). You should observe the following output:
pa1 equal to pa2: false
pa2 equal to pa3: false
pa1 equal to pa3: true
20
Tip Getintothehabitofdevelopingusefulinterfaceswhilehidingimplementations
because it will save you much trouble when maintaining your classes.
Initializing Classes and Objects
Classesandobjectsneedtobeproperlyinitializedbeforetheyareused.You'vealready
learnedthatclassfieldsareinitializedtodefaultzerovaluesafteraclassloads,andcan
be subsequently initialized by assigning values to them in their declarations via class
field initializers ; for example, static int counter = 1; . Similarly, instance
fields are initialized to default values when an object's memory is allocated via new ,
Search WWH ::




Custom Search