Java Reference
In-Depth Information
• Specifythenameofaclassfield'sclass,followedbythememberaccessoper-
ator, followed by the name of the class field from outside the class. Example:
Car.counter
• Specifythenameofaninstancefieldasisfromanyinstancemethod,construct-
or,orinstanceinitializer(discussedlater)inthesameclassastheinstancefield
declaration. Example:
numDoors
• Specifyanobjectreference,followedbythememberaccessoperator,followed
bythenameoftheinstancefieldfromanyclassmethodorclassinitializer(dis-
cussedlater)withinthesameclassastheinstancefielddeclaration,orfromout-
side the class. Example:
Car car = new Car(); car.numDoors =
2;
Although the latter rule might seem to imply that you can access an instance field
from a class context, this is not the case. Instead, you are accessing the field from an
object context.
The previous access rules are not exhaustive because there exist two more field-ac-
cessscenariostoconsider:declaringalocalvariable(orevenaparameter)withthesame
nameasaninstancefieldorasaclassfield.Ineitherscenario,thelocalvariable/para-
meter is said to
shadow
(hide or mask) the field.
Ifyoufindthatyouhavedeclaredalocalvariableoraparameterthatshadowsafield,
youcanrenamethelocalvariable/parameter,oryoucanusethememberaccessoperator
withreservedword
this
(instancefield)orclassname(classfield)toexplicitlyidenti-
fy the field. For example,
Listing 2-6
's
Car(String make, String model,
int nDoors)
constructordemonstratedthislattersolutionbyspecifyingstatements
such as
this.make = make;
to distinguish an instance field from a same-named
parameter.
Representing Behaviors via Methods
Javaletsyourepresentbehaviorsvia
methods
,whicharenamedblocksofcodedeclared
withinaclass'sbody.Entitybehaviorsaredescribedvia
instance methods
.BecauseJava
also supports behaviors that are associated with a class and not with an object, Java
provides
class methods
to describe these class behaviors.
You first learn how to declare and invoke instance methods, and then learn how to
createinstancemethodcallchains.Next,youdiscoverhowtodeclareandinvokeclass
methods,encounteradditionaldetailsaboutpassingargumentstomethods,andexplore
Java'sreturnstatement.Afterlearninghowtoinvokemethodsrecursivelyasanaltern-