Java Reference
In-Depth Information
17
18 public Object pop() {
19 Object o = list.get(getSize() - 1 );
20 list.remove(getSize() - 1 );
21
remove
return o;
22 }
23
24 public void push(Object o) {
25 list.add(o);
26 }
27
28 @Override
29
push
public String toString() {
30
return "stack: " + list.toString();
31 }
32 }
An array list is created to store the elements in the stack (line 4). The isEmpty() method (lines
6-8) returns list.isEmpty() . The getSize() method (lines 10-12) returns list.size() .
The peek() method (lines 14-16) retrieves the element at the top of the stack without remov-
ing it. The end of the list is the top of the stack. The pop() method (lines 18-22) removes the
top element from the stack and returns it. The push(Object element) method (lines 24-26)
adds the specified element to the stack. The toString() method (lines 28-31) defined in the
Object class is overridden to display the contents of the stack by invoking list.toString() .
The toString() method implemented in ArrayList returns a string representation of all the
elements in an array list.
Design Guide
In Listing 11.10, MyStack contains ArrayList . The relationship between MyStack
and ArrayList is composition . While inheritance models an is-a relationship, compo-
sition models a has-a relationship. You could also implement MyStack as a subclass of
ArrayList (see Programming Exercise  11.10). Using composition is better, however,
because it enables you to define a completely new stack class without inheriting the
unnecessary and inappropriate methods from ArrayList .
composition
is-a
has-a
11.14 The protected Data and Methods
A protected member of a class can be accessed from a subclass.
Key
Point
So far you have used the private and public keywords to specify whether data fields and
methods can be accessed from outside of the class. Private members can be accessed only
from inside of the class, and public members can be accessed from any other classes.
Often it is desirable to allow subclasses to access data fields or methods defined in the
superclass, but not to allow nonsubclasses to access these data fields and methods. To accom-
plish this, you can use the protected keyword. This way you can access protected data
fields or methods in a superclass from its subclasses.
The modifiers private , protected , and public are known as visibility or accessibility
modifiers because they specify how classes and class members are accessed. The visibility of
these modifiers increases in this order:
why protected ?
Visibility increases
private, default (no modifier), protected, public
Table 11.2 summarizes the accessibility of the members in a class. Figure 11.5 illustrates how
a public, protected, default, and private datum or method in class C1 can be accessed from a
class C2 in the same package, from a subclass C3 in the same package, from a subclass C4 in
a different package, and from a class C5 in a different package.
 
 
 
Search WWH ::




Custom Search