Java Reference
In-Depth Information
It is important to note that, since class methods operate on the class as a whole (as a blueprint), they
are not able to access instance variables. For example, the following is not allowed:
class Cat {
String name;
static void changeName() {
name = "ANONYMOUS CAT";
}
}
What you can do, however, is the following:
class Cat {
static String preferredFood = "fish";
static String getPreferredFood() {
return preferredFood;
}
static void setPreferredFood(String newFood) {
preferredFood = newFood;
}
}
And call this code as follows:
System.out.println("A cat's preferred food is: "+Cat.getPreferredFood());
Cat.setPreferredFood("milk");
System.out.println("A cat's preferred food is now: "+Cat.getPreferredFood());
This last example illustrates the power of combining class variables with class methods, as they
allow you to create class‐global variables that can be changed if necessary.
Note Again, you are seeing the concept of encapsulation in prac-
tice here. Whereas earlier you would have accessed the class variable
preferredFood by writing Cat.preferredFood directly, you now neatly use the
getPreferredFood and setPreferredFood methods to do so. Does this mean
you can no longer write Cat.preferredFood = “milk” ? The answer is that—
for now—you can, but again, you will see later how you can effectively block
accessing instance variables directly, forcing the use of methods (and prevent-
ing tampering of variables outside their owning class).
constructors
Constructors are special class methods that are used to initialize objects of that class. If you recall
the discussion on final variables, you might remember that you had—at the time—no way to create
 
Search WWH ::




Custom Search