img
Stack mystack1 = new Stack(5);
Stack mystack2 = new Stack(8);
// push some numbers onto the stack
for(int i=0; i<5; i++) mystack1.push(i);
for(int i=0; i<8; i++) mystack2.push(i);
// pop those numbers off the stack
System.out.println("Stack in mystack1:");
for(int i=0; i<5; i++)
System.out.println(mystack1.pop());
System.out.println("Stack in mystack2:");
for(int i=0; i<8; i++)
System.out.println(mystack2.pop());
}
}
Notice that the program creates two stacks: one five elements deep and the other eight
elements deep. As you can see, the fact that arrays maintain their own length information
makes it easy to create stacks of any size.
Introducing Nested and Inner Classes
It is possible to define a class within another class; such classes are known as nested classes.
The scope of a nested class is bounded by the scope of its enclosing class. Thus, if class B is
defined within class A, then B does not exist independently of A. A nested class has access
to the members, including private members, of the class in which it is nested. However, the
enclosing class does not have access to the members of the nested class. A nested class that
is declared directly within its enclosing class scope is a member of its enclosing class. It is
also possible to declare a nested class that is local to a block.
There are two types of nested classes: static and non-static. A static nested class is one
that has the static modifier applied. Because it is static, it must access the members of its
enclosing class through an object. That is, it cannot refer to members of its enclosing class
directly. Because of this restriction, static nested classes are seldom used.
The most important type of nested class is the inner class. An inner class is a non-static
nested class. It has access to all of the variables and methods of its outer class and may refer
to them directly in the same way that other non-static members of the outer class do.
The following program illustrates how to define and use an inner class. The class named
Outer has one instance variable named outer_x, one instance method named test( ), and
defines one inner class called Inner.
// Demonstrate an inner class.
class Outer {
int outer_x = 100;
void test() {
Inner inner = new Inner();
inner.display();
}
// this is an inner class
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home