Data Structures for Java Data Structures for Java
William H. Ford William H. Ford William R. Topp William R. Topp
Chapter 3 Chapter 3
Designing Classes Designing Classes
Bret Ford
The Java Interface The Java Interface
 An interface is a pure abstract classlike An interface is a pure abstract classlike structure.
structure.
 Contains only public abstract methods and Contains only public abstract methods and public final static data.
public final static data.
 Classes implement the interface rather Classes implement the interface rather than extending it.
than extending it.
 Serves as a template for its implementing Serves as a template for its implementing classes.
classes.
The Java Interface The Java Interface
(concluded) (concluded)
 Interface reference variables can be Interface reference variables can be assigned references from any
assigned references from any implementing class.
implementing class.
 Calling a method with an interface Calling a method with an interface
reference variable invokes polymorhpism.
reference variable invokes polymorhpism.
 An interface may be implemented by more An interface may be implemented by more than one class.
than one class.
Declaring an Interface Declaring an Interface
 Use the keyword Use the keyword interface interface . . Example:
Example:
|
|
public interface InterfaceNamepublic interface InterfaceName {{
public static final DATA_NAME = <value>;
public static final DATA_NAME = <value>;
// method declaration uses only a signature // method declaration uses only a signature
public returnType methodName(<parameter list>);
public returnType methodName(<parameter list>);
} }
Implementing an Interface Implementing an Interface
 The relationship between a class and an The relationship between a class and an interface is established by using the
interface is established by using the keyword
keyword implements implements . .
 The implementing class must provide The implementing class must provide
method declarations for each method in method declarations for each method in
the interface.
the interface.
// class interface declaration
public class ClassName implements InterfaceName {
The Measurement Interface The Measurement Interface
 The Measurement interface is a template The Measurement interface is a template for the definition of geometric classes that for the definition of geometric classes that
define the area and perimeter of shapes.
define the area and perimeter of shapes.
public interface Measurement {
public static final double PI = 3.14159265;
double area();
double perimeter();
}
public class Circle implements Measurement {
private double radius;
// creates an instance with // the specified radius
public Circle(double radius) { this.radius = radius; }
// interface method area() returns // PI * radius (squared)
public double area()
{ return PI * radius * radius; }
// interface method perimeter() returns // 2 * PI * radius
public double perimeter()
Circle Class
Circle Class
// access and update methods public double getRadius() { return radius; }
public void setRadius(double radius) { this.radius = radius; }
// returns a description of the object public String toString()
{ return "Circle with radius " + radius; } }
Circle Class (concluded)
Circle Class (concluded)
UML for the Measurement UML for the Measurement
Hierarchy
Hierarchy
Using an Interface Type Using an Interface Type
 An interface reference variable can be An interface reference variable can be assigned any object from a class that assigned any object from a class that
implements the interface, and implements the interface, and
polymorphism applies.
polymorphism applies.
InterfaceName ref;
ImplementingClass obj = new ImplementingClass(...);
ref = obj;
// calls methodName() in ImplementingClass ref.methodName();
public static void resize(Measurement m, double pct)
{
if (m instanceof Rectangle) {
// cast m as a Rectangle Rectangle r = (Rectangle)m;
// use setSides() to resize the // length and width
r.setSides(r.getLength()*pct, r.getWidth()*pct);
}
resize()
resize()
else if (m instanceof Circle) {
// cast m as a Circle Circle c = (Circle)m;
// use setRadius() to resize the radius c.setRadius(c.getRadius()*pct);
} }
resize() (concluded)
resize() (concluded)
Interface Inheritance Interface Inheritance
Hierarchy Hierarchy
 A parent interface may be used to derive a A parent interface may be used to derive a child interface. Use the extends keyword.
child interface. Use the extends keyword.
Example:
public interface DiagonalMeasurement extends Measurement {
public double diagonal();
}
public class Circle implements DiagonalMeasurement {
<declarations of area(), perimeter(), and diagonal()>
}
Extending Interface Extending Interface
Implementations Implementations
 A class that implements an interface can A class that implements an interface can be extended. The subclass implements the be extended. The subclass implements the
interface also.
interface also.
Example:
public class Rectangle implements Measurement { ... }
public class Square extends Rectangle {
<methods area(), perimeter() inherited from Rectangle }
Multiple Interfaces and Multiple Interfaces and
Inheritance Inheritance
 Java only allows a class to extend one Java only allows a class to extend one superclass (single inheritance).
superclass (single inheritance).
 Some languages like C++ allow a class to Some languages like C++ allow a class to inherit multiple superclasses.
inherit multiple superclasses.
Multiple Interfaces and
Multiple Interfaces and
Inheritance (continued)
Inheritance (continued)
Java Answer to Multiple Java Answer to Multiple
Inheritance Inheritance
Allow a superclass to Allow a superclass to implement multiple implement multiple
interfaces.
interfaces.
V C R
i n t e r f a c e A M F M
i n t e r f a c e T V c l a s s
C o m b o T V
Javadoc Javadoc
 Documentation is needed with any Documentation is needed with any programming language.
programming language.
 The javadoc utility produces HTML The javadoc utility produces HTML
documentation for classes and interfaces.
documentation for classes and interfaces.
Javadoc (continued) Javadoc (continued)
 Javadoc comments begin with the Javadoc comments begin with the
marker /** and end with the marker */
marker /** and end with the marker */
 Can use HTML tags in a javadoc comment. Can use HTML tags in a javadoc comment.
 Javadoc tags that produce HTML include: Javadoc tags that produce HTML include:
@param @param - - parameter for a method parameter for a method
@return @return - - identifies method return type identifies method return type
@throws @throws - - specifies exception thrown when specifies exception thrown when an error occurs
an error occurs
Javadoc Example Javadoc Example
/**
* The <em>Circle</em> class provides measurement
* operations for objects that are determined by their radius.
*/
public class Circle implements Measurement { /**
* Creates a circle with the specified radius * @param radius the radius of this object
* @throws IllegalArgumentException if the argument * is negative.
*/
public Circle(double radius) { . . . }
/**
* Returns the area of the circle.
* @return a <code>double</code> having value PI *r (squared).
*/
public double area()
Javadoc Output for Javadoc Output for
Circle Class
Circle Class
Javadoc Output for Javadoc Output for
Circle Class (continued)
Circle Class (continued)
Javadoc Output for Javadoc Output for
Circle Class (continued)
Circle Class (continued)
Javadoc Output for Javadoc Output for
Circle Class (continued)
Circle Class (continued)
Javadoc Output for Javadoc Output for
Circle Class (continued)
Circle Class (continued)
Design Pattern Design Pattern
 Documents the solution to a problem in a Documents the solution to a problem in a very general way.
very general way.
 Singleton design pattern describes a Singleton design pattern describes a
model for building a class that may only model for building a class that may only
have one instance.
have one instance.
public class Dice {
// static reference that identifies // the single instance
private static Dice dice = null;
private Random rnd;
private int dice1, dice2;
// private constructor is called by // the method getDice() to create // a single instance of the class private Dice()
{
// create the random number generator
Dice Class as Example of Dice Class as Example of
Singleton Design Pattern
Singleton Design Pattern
// if no object currently exists, the // method calls the private constructor // to create an instance; in any case, the // method returns the static reference
// variable dice
public static Dice getDice() {
if (dice == null) {
dice = new Dice();
}
Dice Class as Example of Dice Class as Example of
Singleton Design Pattern Singleton Design Pattern
(continued)
(continued)
// toss the dice and update values // for dice1 and dice2
public void toss() {
dice1 = rnd.nextInt(6) + 1;
dice2 = rnd.nextInt(6) + 1;
}
// access methods getOne(), getTwo(), // and getTotal()
. . . }
Dice Class as Example of Dice Class as Example of
Singleton Design Pattern Singleton Design Pattern
(continued)
(continued)
GUI Application Design GUI Application Design
 GUI = "Graphical User Interface". GUI = "Graphical User Interface".
 GUI Components GUI Components
Frame - Main application window Frame - Main application window
Panel - Container to which other components Panel - Container to which other components are added
are added
Label - Displays a string and/or an image Label - Displays a string and/or an image
Text field - Allows input/output of text line Text field - Allows input/output of text line
Button - Responds to pressing with mouse Button - Responds to pressing with mouse
Key Components of a GUI Key Components of a GUI
Application
Application
Inheritance Hierarchy Inheritance Hierarchy
for Java GUI Components
for Java GUI Components
GUI Application Design Pattern GUI Application Design Pattern
<import statements>
public class DiceToss extends JFrame {
< component and application variables>
public static void main(String[] args) {
DiceToss app = new DiceToss();
app.setVisible(true);
}
// constructor creates components and adds them to the frame public DiceToss()
{
<initialize frame attributes, create components>
}
// inner class defines an event handler object
private class EventHandler implements <event interface>
{ }
GUI Design Pattern Import GUI Design Pattern Import
Statements Statements
 Import statements specify the class Import statements specify the class libraries that the application will use libraries that the application will use
import java.awt.*; // original Java AWT
import javax.swing; // Swing component classes
import java.awt.event.*; // Java event classes and interfaces
GUI Design Pattern GUI Design Pattern Application Variables Application Variables
 Declare as application variables the GUI Declare as application variables the GUI components and any data that will be components and any data that will be
accessed by event handlers, utility accessed by event handlers, utility
methods, and inner classes.
methods, and inner classes.
Dice Class Variables Dice Class Variables
class DiceToss extends JFrame { // application variables
private JPanel panelA, panelB;
private JLabel dieLabel1, dieLabel2, totalLabel;
private JTextField totalField;
private JTextArea totalArea;
private JButton tossButton;
private Dice d = Dice.getDice();
private ImageIcon[] diePict = {null,
new ImageIcon("die1.gif"), new ImageIcon("die2.gif"), new ImageIcon("die3.gif"), new ImageIcon("die4.gif"), new ImageIcon("die5.gif"), new ImageIcon("die6.gif")};
. . . }
GUI Application Constructor GUI Application Constructor
 Initializes frame properties and loads the Initializes frame properties and loads the components.
components.
Set title with Set title with
setTitle(titleStr).setTitle(titleStr). setBounds(posX, posY, width, height)setBounds(posX, posY, width, height)
sets the size sets the size of the frame and its position on the screen.
of the frame and its position on the screen.
 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
closes the frame and exits the application closes the frame and exits the application
when the user clicks the close box in the when the user clicks the close box in the
frame.
frame.
GUI Application Constructor GUI Application Constructor
(concluded) (concluded)
 Components in a frame reside in a region Components in a frame reside in a region called the
called the content pane content pane . .
 Use getContentPane() to access the Use getContentPane() to access the
content pane and assign it to a Container content pane and assign it to a Container
reference variable.
reference variable.
Container content = getContentPane();
Container content = getContentPane();
Create and organize components and add them Create and organize components and add them to the content pane.
to the content pane.
public DiceToss() {
. . .
// establish the content pane for the window Container content = getContentPane();
content.setLayout(new BorderLayout());
// panel and labels for the two die pictures JPanel panelA = new JPanel();
dieLabel1 = new JLabel();
dieLabel2 = new JLabel();
panelA.add(dieLabel1);
panelA.add(dieLabel2);
// text area to store results of // successive dice tosses
DiceToss Constructor
DiceToss Constructor
// panel with toss button, total label, // and text field for the total
// the toss button has an action listener // (see next section)
JPanel panelB = new JPanel();
tossButton = new JButton("Toss");
tossButton.addActionListener(new TossEvent());
totalLabel = new JLabel("Total");
totalField = new JTextField(4);
panelB.add(tossButton);
panelB.add(totalLabel);
panelB.add(totalField);
DiceToss Constructor DiceToss Constructor
(continued)
(continued)
// add panels and individual components to the // content pane using compass point constants // for class BorderLayout.
// the text area is embedded in a JScrollPane // to add scroll bars
content.add(panelA, BorderLayout.NORTH);
content.add(new JScrollPane(totalArea), BorderLayout.CENTER);
content.add(panelB, BorderLayout.SOUTH);
}
DiceToss Constructor DiceToss Constructor
(concluded)
(concluded)
Event Listeners Event Listeners
 An event is an action such as a mouse An event is an action such as a mouse click, a button press, or a keystroke.
click, a button press, or a keystroke.
 An event listener is an object that resides An event listener is an object that resides in a component and waits for the
in a component and waits for the
occurrence of an event and handles the occurrence of an event and handles the
actions required by the event.
actions required by the event.
 Add a listener to a component using Add a listener to a component using
addTypeListner(...)
where Type is the type of the event.
where Type is the type of the event.
Action Events Action Events
 An event which indicates that a An event which indicates that a
component-defined action occurred. This component-defined action occurred. This
event is generated by a component (such event is generated by a component (such
as a Button) when the component-specific as a Button) when the component-specific
action occurs (such as being pressed). The action occurs (such as being pressed). The
event is passed to every ActionListener event is passed to every ActionListener
object that registered to receive such object that registered to receive such
events using the component's events using the component's
addActionListener method
addActionListener method
Action Events (continued) Action Events (continued)
 void addActionListener(ActionListener handlerObj)
Adds action listener to a component. The Adds action listener to a component. The
parameter is the event handler that responds parameter is the event handler that responds
to the event.
to the event.
Normally use a private inner class to define an Normally use a private inner class to define an event handler. An inner class has access to all event handler. An inner class has access to all
the variables in the outer class and can update the variables in the outer class and can update
them.
them.
Action Events (concluded) Action Events (concluded)
An action listener event handling class must An action listener event handling class must implement the ActionListener interface. The implement the ActionListener interface. The
interface has only one method interface has only one method
void actionPerformed(ActionEvent ae)
Invoked when an action occurs
Invoked when an action occurs
Action Event Sequence
Action Event Sequence
private class TossEvent implements ActionListener {
public void actionPerformed(ActionEvent ae) {
d.toss();
dieLabel1.setIcon(diePict[d.getOne()]);
dieLabel2.setIcon(diePict[d.getTwo()]);
totalArea.append("Total is " +
d.getTotal() + "\n");
totalField.setText("" + d.getTotal());
} }