Java Reference
In-Depth Information
private data can greatly reduce errors, while increasing the robustness and security of
your programs.
Declaring instance variables with access modifier private is known as data hiding or
information hiding . When a program creates (instantiates) an object of class Account , vari-
able name is encapsulated (hidden) in the object and can be accessed only by methods of
the object's class.
Software Engineering Observation 3.2
Precede each instance variable and method declaration with an access modifier.
Generally, instance variables should be declared private and methods public . Later in
the topic, we'll discuss why you might want to declare a method private .
Conceptual View of an Account Object with Encapsulated Data
You can think of an Account object as shown in Fig. 3.4. The private instance variable
name is hidden inside the object (represented by the inner circle containing name ) and pro-
tected by an outer layer of public methods (represented by the outer circle containing get-
Name and setName ). Any client code that needs to interact with the Account object can do
so only by calling the public methods of the protective outer layer.
name
Fig. 3.4 | Conceptual view of an Account object with its encapsulated private instance
variable name and protective layer of public methods.
3.3 Primitive Types vs. Reference Types
Java's types are divided into primitive types and reference types . In Chapter 2, you worked
with variables of type int —one of the primitive types. The other primitive types are
boolean , byte , char , short , long , float and double , each of which we discuss in this
book—these are summarized in Appendix D. All nonprimitive types are reference types , so
classes, which specify the types of objects, are reference types.
A primitive-type variable can hold exactly one value of its declared type at a time. For
example, an int variable can store one integer at a time. When another value is assigned
to that variable, the new value replaces the previous one—which is lost .
Recall that local variables are not initialized by default. Primitive-type instance vari-
ables are initialized by default—instance variables of types byte , char , short , int , long ,
float and double are initialized to 0, and variables of type boolean are initialized to
 
 
Search WWH ::




Custom Search