Java Reference
In-Depth Information
lation. When attributes are private, object data must be obtained through
methods, not directly. This makes object data safe from unauthorized ac-
cess. The class also contains the methods setDogData(), bark(), and
showDogData().
In order to use a class you must first instantiate an object of the class.
In the VirtualDog program, listed previously, the objects are instantiated
as follows:
// Declare objects of class Dog
Dog dog1 = new Dog();
// First object is named dog1
Dog dog2 = new Dog();
// Second object is dog2
Programmers note:
An object whose state can be changed externally breaks encapsula-
tion.
Each object has:
1. Abehavior (defined by its methods)
2. Astate (determined by its fields)
3. Anidentity,whichmakesitdifferentfromallotherobjectsofthesameclass
In most cases objects have different states, but two objects of the same
class are unique and different, even if they have the same state. For exam-
ple: a GasGauge object encodes the amount of gasoline in a tank. Atruck
with two tanks may have two GasGauge objects. These objects would be
different, even if by chance both of them represented the same number of
gallons of gas. In this case their state would be the same, but each object
would still have its own identity.
Field variables and method variables
Inrelationtotheirlocationintheclass,Javavariablescanbeoftwotypes.
Field variables aredeclaredoutsidethemethods,usuallybeforeanyofthe
methods. Sometimes we just say “fields” to refer to field variables. The
uniquepropertyoffieldvariablesisthattheyareaccessibletoallthemeth-
ods in the class. Variables declared inside methods are called local or
method variables . Local variables are visible inside the method that con-
tains them and their lifetime is limited to duration of the method. For this
reason local variables cannot be accessed by other methods, or by other
classes.Thisexplainswhyyoucannotuseaccessmodifierswithlocalvari-
ables.
Search WWH ::




Custom Search