Java The Complete Reference, Seventh Edition

(Greg DeLong) #1
for(int i=0; i<10; i++)
System.out.println(mystack2.pop());

// these statements are not legal
// mystack1.tos = -2;
// mystack2.stck[3] = 100;
}
}

Although methods will usually provide access to the data defined by a class, this does
not always have to be the case. It is perfectly proper to allow an instance variable to be public
when there is good reason to do so. For example, most of the simple classes in this book
were created with little concern about controlling access to instance variables for the sake of
simplicity. However, in most real-world classes, you will need to allow operations on data
only through methods. The next chapter will return to the topic of access control. As you
will see, it is particularly important when inheritance is involved.

Understanding static


There will be times when you will want to define a class member that will be used
independently of any object of that class. Normally, a class member must be accessed only
in conjunction with an object of its class. However, it is possible to create a member that can
be used by itself, without reference to a specific instance. To create such a member, precede
its declaration with the keywordstatic. When a member is declaredstatic, it can be accessed
before any objects of its class are created, and without reference to any object. You can declare
both methods and variables to bestatic. The most common example of astaticmember is
main( ).main( )is declared asstaticbecause it must be called before any objects exist.
Instance variables declared asstaticare, essentially, global variables. When objects of
its class are declared, no copy of astaticvariable is made. Instead, all instances of the class
share the samestaticvariable.
Methods declared asstatichave several restrictions:


  • They can only call otherstaticmethods.

  • They must only accessstaticdata.

  • They cannot refer tothisorsuperin any way. (The keywordsuperrelates to
    inheritance and is described in the next chapter.)


If you need to do computation in order to initialize yourstaticvariables, you can declare a
staticblock that gets executed exactly once, when the class is first loaded. The following
example shows a class that has astaticmethod, somestaticvariables, and astaticinitialization
block:

// Demonstrate static variables, methods, and blocks.
class UseStatic {
static int a = 3;
static int b;

static void meth(int x) {

Chapter 7: A Closer Look at Methods and Classes 141

Free download pdf