Chapter 5: Enhancing Classes
|
|
|
Presentation slides for |
|
|
|
Java Software Solutions |
|
Foundations of Program Design |
|
Third Edition |
|
|
|
by John Lewis and William Loftus |
|
|
|
Java Software Solutions is published by
Addison-Wesley |
|
|
|
Presentation slides are copyright 2002
by John Lewis and William Loftus. All rights reserved. |
|
Instructors using the textbook may use
and modify these slides for pedagogical purposes. |
|
|
Enhancing Classes
|
|
|
|
|
|
|
Now we can explore various aspects of
classes and objects in more detail |
|
|
|
Chapter 5 focuses on: |
|
object references and aliases |
|
passing objects references as
parameters |
|
the static modifier |
|
wrapper classes |
|
nested classes and inner classes |
|
interfaces |
|
dialog boxes |
|
GUI components, events, and listeners |
References
|
|
|
|
|
|
|
Recall from Chapter 2 that an object
reference variable holds the memory address of an object |
|
|
|
Rather than dealing with arbitrary
addresses, we often depict a reference graphically as a “pointer” to an
object |
|
|
|
|
|
ChessPiece bishop1 = new ChessPiece(); |
|
|
The null Reference
|
|
|
An object reference variable that does
not currently point to an object is called a null reference |
|
An attempt to follow a null reference
causes a NullPointerException to be thrown |
|
For example |
|
|
|
String name; |
|
|
|
declares an object reference
variable, but does not create a String object for it to refer to. |
|
Therefore, the variable name contains a
null reference |
The this Reference
|
|
|
|
The this reference allows an object to
refer to itself. |
|
Inside a method, the this reference can
be used to refer to the currently executing object |
|
For example, |
|
|
|
if(this.position ==
piece2.position) |
|
result = false; |
|
|
|
clarifies which position is being
referenced |
|
The this reference refers to the object
through which the method containing the code was invoked |
The this reference
|
|
|
The this reference can also distinguish
the parameters of a constructor from the corresponding instance variables
with the same names |
Assignment Revisited
|
|
|
|
|
|
|
The act of assignment takes a copy of a
value and stores it in a variable |
|
|
|
For primitive types: |
|
|
|
num2 = num1; |
Reference Assignment
|
|
|
|
|
|
|
For object references, assignment
copies the memory location: |
|
|
|
bishop2 = bishop1; |
Aliases
|
|
|
|
|
|
|
Two or more references that refer to
the same object are called aliases of each other |
|
|
|
One object (and its data) can be
accessed using different reference variables |
|
|
|
Aliases can be useful, but should be
managed carefully |
|
|
|
Changing the object’s state (its
variables) through one reference changes it for all of its aliases |
Testing Objects for
Equality
|
|
|
The == operator compares object
references for equality, returning true if the references are aliases of each
other |
|
A method called equals is defined for
all objects, but unless we redefine it when we write a class, it has the same
semantics as the == operator |
|
|
|
bishop1.equals(bishop2); |
|
|
|
returns true if both references
refer to the same object |
|
We can redefine the equals method to
return true under whatever conditions we think are appropriate |
Garbage Collection
|
|
|
|
|
|
|
When an object no longer has any valid
references to it, it can no longer be accessed by the program |
|
|
|
It is useless, and is called garbage |
|
|
|
Java performs automatic garbage
collection periodically, returning an object's memory to the system for
future use |
Passing Objects as
Parameters
|
|
|
|
|
|
|
Parameters in a Java method are passed
by value |
|
|
|
This means that a copy of the actual
parameter (the value passed in) is stored into the formal parameter (in the
method header) |
|
|
|
Passing parameters is essentially like
an assignment statement |
|
|
|
When an object is passed to a method,
the actual parameter and the formal parameter become aliases of each other |
Passing Objects to
Methods
|
|
|
What you do using a parameter inside a
method may or may not have a permanent effect (outside the method) |
|
|
|
See ParameterPassing.java (page xxx) |
|
See ParameterTester.java (page xxx) |
|
See Num.java (page xxx) |
|
|
|
Note the difference between changing
the reference and changing the object that the reference points to |
ParameterPassing.java
ParameterTester.java
Num.java
The static Modifier
|
|
|
In Chapter 2 we discussed static
methods (also called class methods) that can be invoked through the class
name rather than through a particular object |
|
|
|
For example, the methods of the Math
class are static |
|
|
|
To make a method static, we apply the static
modifier to the method definition |
|
|
|
The static modifier can be applied to
variables as well |
|
|
|
It associates a variable or method with
the class rather than with an object |
Static Variables
|
|
|
|
|
|
|
Static variables sometimes are called class
variables |
|
|
|
Normally, each object has its own data
space |
|
|
|
If a variable is declared as static,
only one copy of the variable exists |
|
|
|
|
|
private static float price; |
|
|
|
|
|
Memory space for a static variable is
created when the class in which it is declared is loaded |
Static Variables
|
|
|
|
|
|
All objects created from the class
share access to the static variable |
|
|
|
Changing the value of a static variable
in one object changes it for all others |
|
|
Static Methods
Static Methods
|
|
|
|
|
|
|
The order of the modifiers can be
interchanged, but by convention visibility modifiers come first |
|
|
|
Recall that the main method is
static; it is invoked by the system
without creating an object |
|
|
|
Static methods cannot reference
instance variables, because instance variables don't exist until an object
exists |
|
|
|
However, they can reference static
variables or local variables |
Static Methods and Static
Variables
|
|
|
|
|
|
Static methods and static variables
often work together |
|
|
|
See CountInstances.java (page xxx) |
|
See Slogan.java (page xxx) |
|
|
CountInstances.java
Slogan.java
Wrapper Classes
|
|
|
A wrapper class represents a particular
primitive type |
|
|
|
For example |
|
|
|
Integer ageObj = new Integer (20); |
|
|
|
uses the Integer class to create an
object which effectively represents the integer 20 as an object |
|
|
|
This is useful when a program requires
an object instead of a primitive type |
Wrapper classes
|
|
|
There is a wrapper class in the Java.lang
package for each primitive type |
|
|
|
(figure 5.4 here) |
Some Methods of the
Integer class
|
|
|
|
(figure 5.5 here) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The Java wrapper classes often contain
useful static constants |
|
For example, the Integer class contains
MIN_VALUE and MAX_VALUE which hold the smallest and largest int values |
Keyboard Input Revisited
|
|
|
The Keyboard class was introduced in
Chapter 2 to facilitate input from the keyboard |
|
Input can be read from the keyboard
without using the Keyboard class |
|
See Wages2.java (page xxx) |
Wages2.java
Java I/O
|
|
|
Java I/O is accomplished using objects
that represent streams of data |
|
|
|
A stream is an ordered sequence of
bytes |
|
|
|
The System.out object represents a
standard output stream, which defaults to the monitor screen |
|
|
|
Reading keyboard input is more
complicated |
Reading Keyboard Input
|
|
|
|
First, we must establish an input
stream |
|
The System.in object is used to create
an InputStreamReader object |
|
The InputStreamReader object is used to
create a BufferedReader object |
|
This creates an input stream that
treats input as characters and buffers them so that input can be read a line
at a time |
|
|
|
The readLine method of the BufferedReader
class reads an entire line of input as a String |
|
the parseInt method of the Integer
wrapper class and the parseDouble method of the Double class convert the
input string |
Reading Keyboard Input
|
|
|
Problems that arise in reading or
converting a value manifest themselves as exceptions |
|
|
|
The main method in Wages2 may throw an IOException,
as acknowledged in the throws clause in the method header |
|
|
|
The Keyboard class hides these aspects
of keyboard input |
|
|
|
I/O and exceptions are explored further
in Chapter 8 |
Nested Classes
|
|
|
|
|
|
In addition to containing data and
methods, a class can contain other classes |
|
|
|
A class declared within another class
is called a nested class |
|
|
Nested Classes
|
|
|
|
|
|
A nested class has access to the
variables and methods of the enclosing class, even if they are declared
private |
|
|
|
In certain situations this makes the
implementation of the classes easier because they can share information
easily |
|
|
|
Furthermore, the nested class can be
protected by the enclosing class from external use |
|
|
|
This is a special relationship and
should be used with care |
Nested Classes
|
|
|
|
|
|
|
A nested class produces a separate
bytecode file |
|
|
|
If a nested class called Inside is
declared in an outer class called Outside, two bytecode files will be
produced: |
|
|
|
Outside.class |
|
Outside$Inside.class |
|
|
|
Nested classes can be declared as
static, in which case they cannot refer to instance variables or methods |
|
|
|
|
Inner Classes
|
|
|
A nonstatic nested class is called an inner
class |
|
|
|
An inner class is associated with each
instance of the enclosing class |
|
|
|
An instance of an inner class can exist
only within an instance of an enclosing class |
|
|
|
See TestInner.java (page xxx) |
|
See Outer.java (page xxx) |
TestInner.java
Outer.java
Interfaces
Interfaces
|
|
|
|
|
|
|
A Java interface is a collection of
abstract methods and constants |
|
|
|
An abstract method is a method header
without a method body |
|
|
|
An abstract method can be declared
using the modifier abstract, but because all methods in an interface are
abstract, usually it is left off |
|
|
|
An interface is used to define a set of
methods formally that a class will implement |
|
|
|
See Complexity.java (page xxx) |
Complexity.java
Interfaces
Interfaces
|
|
|
|
|
|
An interface cannot be instantiated |
|
|
|
Methods in an interface have public
visibility by default |
|
|
|
A class formally implements an
interface by |
|
stating so in the class header |
|
providing implementations for each
abstract method in the interface |
|
|
|
If a class asserts that it implements
an interface, it must define all methods in the interface or the compiler
will produce errors. |
|
|
|
See Question.java (page xxx) |
Question.java
Interfaces
|
|
|
A class that implements an interface
can implement other methods as well |
|
A class can implement multiple
interfaces |
|
|
|
class ManyThings implements
interface 1, inerface2, interface3 |
|
{ |
|
// all methods of all
interfaces |
|
} |
|
The interfaces are listed in the
implements clause, separated by commas |
|
The class must implement all methods in
all interfaces listed in the header |
|
|
Interfaces
|
|
|
See MiniQuiz.java (page xxx) |
Interfaces
Interfaces
|
|
|
In addition to, or instead of abstract
methods, an interface can contain constants |
|
|
|
When a class implements an interface,
it gains access to all its constants |
Interfaces
|
|
|
The Java standard class library
contains many helpful interfaces |
|
|
|
The Comparable interface contains an
abstract method called compareTo, which is used to compare two objects |
|
|
|
The String class implements Comparable
which gives us the ability to put strings in alphabetical order |
|
|
|
The Iterator interface contains methods
that allow the user to move easily through a collection of objects |
The Comparable Interface
|
|
|
The Comparable interface provides a
common mechanism for comparing one object to another |
|
|
|
if (obj1.compareTo(obj2) < 0) |
|
System.out.println (“obj1 is
less than obj2”); |
|
|
|
The result is negative is obj1 is less
that obj2, 0 if they are equal, and positive if obj1 is greater than obj2 |
The Iterator Interface
|
|
|
The Iterator interface provides a means
of moving through a collection of objects, one at a time |
|
|
|
The hasNext method returns a boolean
result (true if there are items left to process) |
|
|
|
The next method returns an object |
|
|
|
The remove method removes the object
most recently returned by the next method |
Dialog Boxes
|
|
|
A dialog box is a graphical window that
pops up on top of any currently active window for the user |
|
|
|
The Swing package contains a class
called JOptionPane that simplifies the creation and use of basic dialog boxes |
|
|
|
(Figure 5.7 here) |
Dialog Boxes
|
|
|
There are three categories of JOptionPane
dialog boxes |
|
|
|
A message dialog displays an output
string |
|
|
|
An input dialog presents a prompt and a
single input text field |
|
|
|
A confirm dialog presents the user with
a simple “yes-or-no” question |
|
|
|
See EvenOdd.java (page xxx) |
EvenOdd.java
Graphical User Interfaces
|
|
|
|
A Graphical User Interface (GUI) is
created with at least three kinds of objects |
|
components |
|
events |
|
listeners |
|
|
|
A GUI component defines a screen
element to display information or to allow the user to interact with the
program |
|
push buttons |
|
text fields |
|
labels |
|
etc. |
Containers
|
|
|
|
A container is a special component that
holds and organizes other components |
|
|
|
a dialog box |
|
an applet |
Events
|
|
|
|
|
|
An event is an object that represents
some activity to which we may want to respond |
|
|
|
For example, we may want our program to
perform some action when the following occurs: |
|
the mouse is moved |
|
a mouse button is clicked |
|
the mouse is dragged |
|
a graphical button is clicked |
|
a keyboard key is pressed |
|
a timer expires |
|
|
|
Events often correspond to user
actions, but not always |
Events and Listeners
|
|
|
|
|
|
The Java standard class library
contains several classes that represent typical events |
|
|
|
Certain objects, such as an applet or a
graphical button, generate (fire) an event when it occurs |
|
|
|
Other objects, called listeners, wait
for events to occur |
|
|
|
We can write listener objects to do
whatever we want when an event occurs |
Events and Listeners
Listener Interfaces
|
|
|
|
|
|
We can create a listener object by
writing a class that implements a particular listener interface |
|
|
|
The Java standard class library
contains several interfaces that correspond to particular event categories |
|
|
|
For example, the MouseListener
interface contains methods that correspond to mouse events |
|
|
|
After creating the listener, we add the
listener to the component that might generate the event to set up a formal
relationship between the generator and listener |
|
|
Creating GUIs
|
|
|
|
To create a program with a GUI |
|
define and set up the components |
|
create listener objects |
|
create the relationships between the
listeners and the components which generate events of interest |
|
define what happens in response to each
event of interst |
|
|
|
See PushCounter.java (page xxx) |
PushCounter.java
Creating GUIs
|
|
|
A push button is a component that
allows the user to initiate an action with the press of the mouse button |
|
|
|
A label is a component that displays a
line of text |
|
|
|
The init method of an applet sets up
the GUI and adds each component to the applet container (the content pane) |
|
|
|
The content pane is retrieved using the
getContentPane method |
|
|
|
A JButton generates an action event |
Creating GUIs
|
|
|
A listener object commonly is created
by defining a class that implements a listener interface |
|
|
|
For example, the interface for an
action event is called ActionListener, which defines only the actionPerformed
method |
|
|
|
The ButtonListener class implements the
ActionListener interface |
|
|
|
When the button is pushed, the JButton
object invokes the actionPerformed method, generating an ActionEvent |
GUI Applications
|
|
|
|
A frame is a container component used
for stand-alone GUI-based applications |
|
|
|
A panel is a container, but, unlike a
frame, it cannot be displayed on its own |
|
it must be added to another container |
|
it helps organize the components in a
GUI |
|
|
|
See Fahrenheit.java (page xxx) |
|
See FahrenheitGUI.java (page xxx) |
Summary
|
|
|
|
Chapter 5 has focused on: |
|
object references and aliases |
|
passing objects references as
parameters |
|
the static modifier |
|
wrapper classes |
|
nested classes and inner classes |
|
interfaces |
|
dialog boxes |
|
GUI components, events, and listeners |
|
|