Java Reference
In-Depth Information
Remembering data: adding variables to the subclass definition
Now assume that the user of subclass OurFrame wants to be able to retrieve the
old value of the title. They have dragged the window to another spot and would
like the ability to remember where it used to be. We can help them out by plac-
ing a field in OurFrame that gives the previous title. Variables are used to remem-
ber values, so we introduce a variable to remember the previous title:
public class OurFrame extends JFrame {
/** class invariant: previousTitle is previous title (initially "")*/
private String previousTitle;
Style Note
The declaration of field previousTitle differs from declarations you have
seen because of the access modifier private , which indicates that the variable
can be accessed only in this class itself. No other class will be able to refer to it
directly. Instead, they must use the setter and getter methods for it, which get val-
ues and store values in fields. You see the variable grayed out in the folder of Fig.
The comment that precedes the declaration of the field has the title “class
invariant”. A class invariant describes what the values of the fields should con-
tain, and it is the duty of each method that is called to ensure that that descrip-
tion is true when the method is finished executing. We often write such a class
invariant, and whenever we write a method, we make sure that the class invari-
ant is true when the method is finished.
Every object of type OurFrame will have its own copy of previousTitle .
Take a look at procedure setTitleToOrigin in Fig. 1.10. It now contains
two statements instead of one. The first statement evaluates the current title,
using a call to function getTitle , and stores the current title in field
previousTitle . The second statement then sets the title of the window, as
before. When the method is called, the statements are executed one at a time, in
the order in which they appear.
Figure 1.10 contains a getter method, named getPreviousTitle . This
method is a function , not a procedure. We know this because the return type is
show() hide()
setLocation( int , int ) etc.
ourWindow a1
Figure 1.9:
A manila folder for instance ours of class OurFrame
Search WWH ::

Custom Search