Attributes represent the state of the object because they store the information about the object. For our example, the Cabbie
class has attributes that store the name of the company, the name of the cabbie, and the cab assigned to the cabbie. For example, the first attribute stores the name of the company:
private static String companyName = "Blue Cab Company";
Note here the two keywords private
and static
. The keyword private
signifies that a method or variable can be accessed only within the declaring object.
The static
keyword signifies that there will be only one copy of this attribute for all the objects instantiated by this class. Basically, this is a class attribute. (See Chapter 3, “Advanced Object-Oriented Concepts,” for more discussion on class attributes.) Thus, even if 500 objects are instantiated from the Cabbie
class, only one copy will be in memory of the companyName
attribute (see Figure 4.2).
The second attribute, name
, is a string that stores the name of the cabbie:
private String name;
This attribute is also private so that other objects cannot access it directly. They must use the interface methods.
The myCab
attribute is a reference to another object. The class, called Cab
, holds information about the cab, such as its serial number and maintenance records:
private Cab myCab;
Note that at this point, only a reference to a Cab
object is created; there is no memory allocated by this definition.
18.117.146.113