What We Will Cover
Continuations
Homework Questions?
Questions from last class?
A programmer wants to create an application that allows employees to log hours in a user interface. Which of the following will be the first step in developing this application?
- design the classes
- prototype the user interface
- deploy the application
- analyze the current procedure for logging hours
^ top
12.1: Introduction to Inheritance
Objectives
At the end of the lesson the student will be able to:
- Describe how inheritance is used in Java
- Use inheritance in your programs
- Inherit from Java's classes
|
^ top
12.1.1: Introducing Inheritance
Inheritance: the ability to define new classes from existing ones.
- Inheritance is one of the important ideas of object-oriented programming
- It lets you define a class that inherits all the public and protected fields and methods from another class
- A class that inherits is called the subclass (derived, child)
- A class that is inherited from is called the superclass (base, parent)
- In a subclass, you define new fields and methods not found in the superclass
- Here is a UML diagram showing the inheritance of one class from another

About the Diagram
- First section of class diagram contains the class name
- Second section describes the attributes (data variables)
- Bottom section describes the operations (methods)
- Minus sign (-) marks attributes and operations that cannot be accessed by other classes
- Plus sign (+) marks attributes and operations that can be accessed by other classes
- Parameters are listed in parenthesis separated by commas
- Name of the parameter is followed by a colon and the data type
- Methods that return values are followed by a colon and the return type
- The upward pointing arrow indicates inheritance
^ top
12.1.2: Inheritance Example
- Deriving a new class from an existing one requires the
extends clause
- Syntax:
public class SubclassName extends SuperclassName
A subclass can only extend one superclass
- Java does not support multiple inheritance
- Interfaces (discussed later today) achieve much of the same effect
Example Superclass
public class Person {
private String name;
public Person() {
name = "No name yet";
}
public Person(String initialName) {
name = initialName;
}
public String getName() {
return name;
}
public void setName(final String newName) {
name = newName;
}
public void printAttributes() {
System.out.println("Name: " + name);
}
public boolean sameName(Person otherPerson) {
return (this.name.equalsIgnoreCase(
otherPerson.name));
}
public void special() {
System.out.println("I am special");
}
}
Example Subclass
public class Student extends Person {
private int studentNumber;
public Student() {
super();
studentNumber = 0;
}
public Student(String name) {
super(name);
studentNumber = 0;
}
public Student(String name, int number) {
super(name);
studentNumber = number;
}
public void printAttributes() {
super.printAttributes();
System.out.println("Student Number : "
+ studentNumber);
special();
}
}
Example Test Application
public class StudentApp {
public static void main(String[] args) {
Student noName = new Student();
Student ed = new Student("Ed", 10);
Student buford = new Student("Buford");
noName.printAttributes();
ed.printAttributes();
buford.printAttributes();
System.out.println(ed instanceof Student);
}
}
^ top
12.1.3: Class Hierarchies
- Classes can be derived from derived classes
- Subclass objects can be treated as superclass objects
- Child classes can be parent classes
- Classes higher in the hierarchy are called ancestor classes
- Classes lower in the hierarchy are called descendent classes
- Note that inheritance describes an is-a relationship
- Reverse is not true
Window is not always a Dialog
For Example
- Following is taken from the Java API
- Shows that a superclass can have more than one subclass
- For instance,
Window has two subclasses

Another Way to Draw Inheritance
- There are many ways to draw inheritance diagrams
- Following is another way to show the inheritance hierarchy for Container
- Note that the superclass is always drawn higher than the subclass
Container
|
+--Panel
| |
| +--Applet
|
+--Window
|
+--Frame
|
+--Dialog
Designing with Inheritance
- Note in the inheritance diagram above that a Frame is a type of Window
- When using inheritance in an application, important to keep "is a" in mind
- Make sure a subclass has an is-a relationship with the superclass
- A subclass must be a type of a superclass
- Which of the following are valid is-a relationships?
- Car ==> Vehicle
- Car ==> Motorcycle
- Student ==> Person
- Student ==> College
- Substitute the words "is a type of" for the arrow (==>)
^ top
12.1.4: Overriding Methods
- Following is an example of adding an attribute in a subclass
public class Student extends Person {
private int studentNumber;
Note that an attribute for the student number has been added
A Student has this attribute in addition to a name
name is inherited from Person
Following is an example of overriding a method in a subclass
public void printAttributes() {
System.out.println("Name: " + getName());
System.out.println("Student Number : "
+ studentNumber);
}
Both superclass and subclass has a printAttributes method
Both methods have the same parameters (i.e. none)
- Thus, they have the same signature
The method from the subclass overrides (replaces) the superclass method
Will not override the superclass if the parameters are different
- Would have different signatures
Called overriding -- not to be confused with overloading
You can still call an overridden method using the keyword super
public void printAttributes() {
super.printAttributes();
System.out.println("Student Number : "
+ studentNumber);
}
Overriding Verses Overloading
| Overriding |
Overloading |
|
|
- Same signature
- One method in superclass, one in subclass
|
- Different signature
- Both methods can be in same class
|
Access Modifiers and Inheritance
private instance variables from the parent class are not available by name in derived classes
- You use accessor methods to change them
private methods are not inherited either
- You use
public or protected to allow methods or variables to be inherited
- Only "helper" methods should be declared private
^ top
12.1.5: Constructors and Inheritance
Superclass Constructor
- Constructors are not inherited by a subclass
- Instead, superclass constructors are called by the subclass constructor
- Superclass constructors are called either implicitly or explicitly using
super()
Examples of Subclass Constructors
- Keyword
extends in first line
- Defines a subclass based on the superclass
public class Student extends Person {
private int studentNumber;
public Student() {
super();
studentNumber = 0;
}
...
Default constructor initializes attribute studentNumber to 0
super() calls the parent's default constructor
Included automatically by Java if not explicitly stated
super() must be first action in a constructor definition
...
public Student(String name, int number) {
super(name);
studentNumber = number;
}
The overloaded constructor passes the parameter newName to the constructor of the superclass
After which the Student() constructor initializes the instance variable studentNumber
More About Subclass Constructors
- Constructors cannot be overridden
- Constructors can be overloaded, but only in the same class
- Also, constructors can call other constructors -- known as chaining
- Use
super() to invoke a constructor in the superclass
super() must be the first action taken by the constructor
^ top
12.1.6: Summary
- You can use inheritance to create a subclass (derived, child)
- Inherits fields and methods from a superclass (base, parent)
- Inheritance allows you to develop hierarchies of classes
- Subclasses can have access to fields and methods of the hierarchy
- Deriving a new class from an existing one requires the
extends clause
public class SubclassName extends SuperclassName
You can define new fields and methods in a subclass
You can call constructors of the superclass using the super() method
super(name);
If a method in a subclass has the same signature as a method in the superclass, the method from the subclass overrides (replaces) the superclass method
- Will not override the superclass if the parameters are different
- Would have a different signature
^ top
Exercise 12.1
With a partner, if needed, take 5 minutes to complete the following:
- Start a text file named exercise12.txt.
- Prepare the exercise header as described in the HowTo on submitting exercises
- Label this exercise: Exercise 12.1
- Submit all exercises for this lesson in one file unless instructed otherwise
- Complete the following and record the answers to any questions in exercise12.txt.
Specifications
- Given the code shown below, which one of the following constructors could be added to class
MySub without causing a compile time error?
class MySuper {
int number;
MySuper(int i) {
number = i;
}
}
public class MySub extends MySuper {
int count;
MySub(int cnt, int num) {
super(num);
count = cnt;
}
// Add new constructor here
}
MySub() {}
MySub(int cnt) { super(); count = cnt; }
MySub(int cnt) { count = cnt; super(cnt); }
MySub(int cnt) { super(cnt); count = cnt; }
- Record your answer in exercise12.txt.
^ top
12.2: Introduction to Interfaces
Objectives
At the end of the lesson the student will be able to:
- Code abstract classes
- Declare interfaces
- Implement interfaces
|
^ top
12.2.1: About Interfaces
- An interface is a class-like mechanism
- An interface can contain:
- Static constants
- Method declarations
- The advantage of an interface is that it provides a separate inheritance hierarchy
- A class can only inherit from one class but can implement many interfaces
- Provides many of the advantages of multiple inheritance without the drawbacks
When Will You Need Interfaces?
- You rarely need to code your own interface
- However, you often need to implement interfaces in the Java API
- In particular, interfaces are used to code graphical user interfaces
- Interfaces are an integral part of event handling
- Such as when a user clicks a mouse button
^ top
12.2.2: Implementing Interfaces
- Any class can choose to implement zero or more interfaces
- Syntax:
public class ClassName [extends SuperClass]
[implements Interface1 [, Interface2]...] { }
Classes implementing an interface add the keyword implements in the class header
After the implements keyword, code a comma-delimited list of interface names
A class that implements an interface must implement all methods of the interface
For Example
- We define an interface named
Drawable
public interface Drawable {
public static final int UNFILLED = 0;
public static final int FILLED = 1;
public void draw();
}
The interface declares one method
public void draw();
Any class that implements Drawable must implement all methods of the interface
public class Circle implements Drawable {
// Other code for the Circle class...
// Implement the draw() method
public void draw() {
System.out.println("Drawing a circle");
}
}
^ top
12.2.3: Interfaces as Arguments
- A method that accepts an interface as an argument can accept any object implementing that interface
- The accepting method can in turn call the implemented method
For Example
- We define a class that draws various shapes
public class DrawingApp {
// Other code for the DrawingApp class...
public void drawShape(Drawable shape) {
shape.draw();
}
public static void main(String[] args) {
DrawingApp app = new DrawingApp;
Circle circ = new Circle();
app.drawShape(circ);
}
}
Our application can define a method with a Drawable parameter
public void drawShape(Drawable shape)
Any class that implements the Drawable interface can be passed to this method
Circle circ = new Circle();
app.draw(circ);
This allows the method accepting Drawable to call the implemented method
public void drawShape(Drawable shape) {
shape.draw();
}
^ top
12.2.4: Summary
- An interface can contain:
- Static constants
- Method declarations
- The advantage of an interface is that classes can implement many interfaces
- Provides many of the advantages of multiple inheritance without the drawbacks
- Any class can choose to implement zero or more interfaces
- Syntax:
public class ClassName [extends SuperClass]
[implements Interface1 [, Interface2]...] { }
A method that accepts an interface as an argument can accept any object that implements that interface
This technique is used extensively in event-driven programming
^ top
Exercise 12.2
- Label this exercise: Exercise 12.2
- Submit all exercises for this lesson in one file unless instructed otherwise
- Complete the following and record the answers to any questions in exercise12.txt.
Specifications
- Compile and run the
HelloButton class shown below.
Q1: What interface does the program implement?
- Examine the API documentation for the ActionListener interface.
Q2: What method must a class implement to become an ActionListener?
Q3: What is the name of the class and method that accepts an ActionListener interface?
import javax.swing.*;
import java.awt.event.*;
public class HelloButton extends JFrame
implements ActionListener {
public static void main(String[] args) {
HelloButton hb = new HelloButton();
}
public HelloButton() {
super("Hello Button Application");
JButton exitButton = new JButton("Hello");
getContentPane().add(exitButton);
exitButton.addActionListener(this);
setSize(300, 150);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
System.out.println("Goodbye!");
System.exit(0);
}
}
^ top
12.3: Graphical-User Interfaces
Objectives
At the end of the lesson the student will be able to:
- Describe the basic operation of Graphical User Interfaces (GUIs)
- Identify the common Swing components
|
^ top
12.3.1: About Graphical User Interfaces (GUIs)
- Graphical User Interface (GUI) -- pronounced "gooey"
- Graphical: not just text or characters but includes windows, menus, buttons, etc.
- User: person using the program via mouse, keyboard, etc.
- Interface: interaction with the program using visual controls, widgets, etc.
- Most modern programs use a GUI
- Typical graphical elements include:
- Window: portion of screen that serves as a smaller screen within the screen
- Menu: list of alternatives offered to user
- Button: looks like a button that can be pressed
- Objects that make up a GUI are called components
- Java provides two sets of components: AWT and Swing
- AWT (Abstract Window Toolkit) is the older set of components
- Relies on the underlying visual components of the operating system
- GUIs look different on each operating system
- Swing (like the dance) is the newer set of components
- Draws its own visual components on the screen
- Originates from AWT components
- Adds new capabilities
- We will use Swing components
Example GUI
^ top
12.3.2: Event-Driven Programming
- Programs with GUIs often use Event-Driven Programming
- Program waits for events to occur and then responds
- Examples of events include:
- Clicking a mouse button
- Dragging the mouse
- Pressing a key on the keyboard
Terminology
- Firing an event: when an object generates an event
- Listener: object that waits for events to occur
- Event handler: method that responds to an event
- Component: a visual object that responds to user actions
- Container: an object that holds other objects
Traditional "Uneventful" Programming vs. Event-Driven Programming
| "Uneventful" |
Event Driven |
| Which action is taken next determined by the computer |
Which action taken next determined by the user |
| Program starts in main and ends after the last statement completes |
Program starts in main but ends when the user says to end |
| Programs are lists of instructions performed in order with some branching |
Programs are objects that can fire events and objects that react to events |
| Program performed by one agent -- the computer |
Program is interaction between user and computer |
^ top
12.3.3: GUI Components
- Java has two special libraries for implementing GUI interfaces: AWT and Swing
- AWT was the original library that shipped with Java 1.0
- Swing was added in Java 2 (SDK 1.2) in the package javax.swing
- You can easily identify Swing components because their names start with "J"
- Swing classes inherit from AWT classes, extending their capabilities
- The component hierarchy is:

^ top
12.3.4: Component Categories
- GUI components fall into three categories
Top-Level Containers
- Basic window structure that ties the GUI into the operating system
- Includes capabilities such as borders and resizability
- Holds intermediate containers and atomic components
- Every GUI program must have one top-level container
- Some of the frequently used components are:
| Component |
Description |
| JFrame |
A top-level window with a title, border and buttons for closing and iconifying the window. |
| JApplet |
Container for applets, which are small programs that run inside a Web browser |
| JOptionPane |
Limited window that makes it easy to pop up a standard dialog box that prompts users for a value or informs them of something. |
Intermediate Containers
- Graphical object displayed in a top-level container
- Can also hold other intermediate containers and atomic components
- Used to simplify placement of atomic components
- Some of the frequently used components are:
| Component |
Description |
| JPanel |
Provides a general-purpose container for atomic components and other intermediate containers. |
| JRootPane |
A container used behind the scenes by JFrame, JApplet and other containers. |
Atomic Components
- Graphical objects used to accept input or display information
- Must be placed in a container using the
add method
- Some of the frequently used components are:
| Component |
Description |
| JButton |
Display area that triggers an event when clicked. |
| JComboBox |
Drop-down list of items from which the user can make a selection by clicking an item in the list or possibly by typing into a box. |
| JCheckBox |
GUI component that can be selected or deselected and displays its state to the user as a checked square. |
| JRadioButton |
GUI component that can be selected or deselected and displays its state to the user as a filled or unfilled circle. |
| JLabel |
Display area for text or icons |
| JTextField |
Single-line display and input area for the user to enter data from the keyboard. |
| JTextArea |
Multi-line display and input area for the user to enter data from the keyboard. |
Further Information
^ top
12.3.5: Summary
- Graphical user interfaces use a type of programming known as event-driven programming
- Programs wait for the user to create an event and then responds
- Java provides special libraries for implementing GUI interfaces, the newer of which is called Swing
- GUI components fall into three categories:
- Top-level containers: basic window structure that ties the GUI into the operating system
- Intermediate containers: used to hold other components
- Atomic components: graphical objects used to accept input or display information
^ top
Exercise 12.3
With a partner, if needed, take 5 minutes to complete the following:
- Start a text file named exercise12.txt.
- Prepare the exercise header as described in the HowTo on submitting exercises
- Label this exercise: Exercise 12.3
- Submit all exercises for this lesson in one file unless instructed otherwise
- Complete the following and record the answers to the questions in exercise12.txt.
Specifications
- What are the three types of GUI components?
- What elements of a GUI does a user see?
^ top
12.4: Creating a Simple GUI Application
Objectives
At the end of the lesson the student will be able to:
- Work with frames
- Add a panel to a frame
- Add buttons to a panel
- Handle button events
|
^ top
12.4.1: Working With Frames
- A
JFrame is a top-level component commonly used with Java applications
- It inherits many methods from both the
Frame and Window class
- By default, all frames are 0 x 0 pixels and open in the top left corner of the screen
- To code a GUI application, you typically extend
JFrame
public class HelloWindow extends JFrame
To close a JFrame, you often use the method setDefaultCloseOperation()
setDefaultCloseOperation(EXIT_ON_CLOSE);
For Example
import javax.swing.*;
public class HelloFrame extends JFrame {
public final static int X_LOC = 100, Y_LOC = 100,
WIDTH = 300, HEIGHT = 150;
public HelloFrame() {
super("Hello Frame Application");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setBounds(X_LOC, Y_LOC, WIDTH, HEIGHT);
setVisible(true);
}
public static void main(String[] args) {
new HelloFrame();
}
}
Commonly Used Methods of the Frame Class
Commonly Used Methods of the Window Class
| Method |
Description |
| hide() |
Hides this window without closing it. |
| pack() |
Size this window to fit the preferred size and layout of its components. |
| show() |
Makes this window visible. |
Commonly Used Methods of the Component Class
^ top
12.4.2: Adding a Panel to a Frame
- After you create a frame, you need to add components to it
- One component you often add is a
JPanel
- The
JPanel is an intermediate container
- You use a
JPanel to contain atomic components and other intermediate containers
- The code to add a
JPanel to the content pane of a JFrame is:
JPanel panel = new JPanel();
Container contentPane = getContentPane();
contentPane.add(panel);
You can add components, such as buttons, directly to the content pane
However, you often add components to a panel and then add the panel to the content pane
This helps you to group components so your code is easier to read and understand
Methods to Add Components to the Content Pane
^ top
12.4.3: Adding Buttons to a Panel
- Button: a component the user clicks to trigger a specific action
- Basic buttons are created with class JButton
- You can add a button to a panel like this:
JPanel panel = new JPanel();
JButton button = new JButton("Hello");
panel.add(button);
The first two statements create the panel and the button
The third statement adds the button to the panel
The following example adds two buttons to a panel and then adds the panel to a frame
For Example
import java.awt.*;
import javax.swing.*;
public class HelloFrame2 extends JFrame {
public final static int X_LOC = 100, Y_LOC = 100,
WIDTH = 300, HEIGHT = 150;
private JButton helloButton;
private JButton exitButton;
public HelloFrame2() {
super("Hello Frame Application");
setDefaultCloseOperation(EXIT_ON_CLOSE);
helloButton = new JButton("Hello");
exitButton = new JButton("Exit");
JPanel panel = new JPanel();
panel.add(helloButton);
panel.add(exitButton);
Container contentPane = getContentPane();
contentPane.add(panel);
setBounds(X_LOC, Y_LOC, WIDTH, HEIGHT);
setVisible(true);
}
public static void main(String[] args) {
new HelloFrame2();
}
}
Commonly Used Constructors of the JButton Class
Some Methods of the JButton Class
^ top
12.4.4: Handling Button Events
- So far the buttons do not respond when the user clicks them
- To make them respond, you need to add code that is executed when a button is clicked
- This is known as event-handling code
- The following only shows how to handle button events
- However, you use the same principles to handle other types of events
How To Handle Action Events
- Specify that a class implements the
ActionListener interface
public class HelloFrame3 extends JFrame
implements ActionListener {
- Register the
ActionListener object with the button by calling the addActionListener() method
helloButton.addActionListener(this);
- Implement the
ActionListener interface by coding the actionPerformed() method
public void actionPerformed(ActionEvent ae) {
Object source = ae.getSource();
if (source == helloButton) {
JOptionPane.showMessageDialog(this, "Hello");
} else if (source == exitButton) {
System.out.println("Goodbye!");
System.exit(0);
} else {
System.out.println("Unknown ActionEvent");
}
}
For Example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class HelloFrame3 extends JFrame
implements ActionListener {
public final static int X_LOC = 100, Y_LOC = 100,
WIDTH = 300, HEIGHT = 150;
private JButton helloButton;
private JButton exitButton;
public HelloFrame3() {
super("Hello Frame Application");
setDefaultCloseOperation(EXIT_ON_CLOSE);
helloButton = new JButton("Hello");
helloButton.addActionListener(this);
exitButton = new JButton("Exit");
exitButton.addActionListener(this);
JPanel panel = new JPanel();
panel.add(helloButton);
panel.add(exitButton);
Container contentPane = getContentPane();
contentPane.add(panel);
setBounds(X_LOC, Y_LOC, WIDTH, HEIGHT);
setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
Object source = ae.getSource();
if (source == helloButton) {
String msg = "Hey";
JOptionPane.showMessageDialog(this, msg);
} else if (source == exitButton) {
System.out.println("Goodbye!");
System.exit(0);
} else {
System.out.println("Unknown ActionEvent");
}
}
public static void main(String[] args) {
new HelloFrame3();
}
}
^ top
12.4.5: Summary
- Most Java GUI applications inherit from a
JFrame
public class HelloWindow extends JFrame
To close a JFrame, you often use the method setDefaultCloseOperation()
setDefaultCloseOperation(EXIT_ON_CLOSE);
To add components to a JFrame, you often use a JPanel as an intermediate container
To add button components, you use the JButton class
The code for adding buttons is something like:
JPanel panel = new JPanel();
helloButton = new JButton("Hello");
panel.add(helloButton);
Container contentPane = getContentPane();
contentPane.add(panel);
To make a button respond when clicked, you add an ActionEvent handler
There are three steps for adding an ActionEvent handler:
- Specify that a class implements the
ActionListener interface
public class HelloFrame3 extends JFrame
implements ActionListener {
- Register the
ActionListener object with the button by calling the addActionListener() method
helloButton.addActionListener(this);
- Implement the
ActionListener interface by coding the actionPerformed() method
public void actionPerformed(ActionEvent ae) {
// event handling code
}
^ top
Exercise 12.4
- Label this exercise: Exercise 12.4
- Submit all exercises for this lesson in one file unless instructed otherwise
- Complete the following and record the answers to any questions in exercise12.txt.
Specifications
- Compile and run the
HelloFrame3 application shown below.
- Add three more
JButtons to the HelloFrame3 application.
Q1: What affected the order in which the buttons were displayed?
Q2: If you make the window very narrow, what happens to the buttons?
- Add event handlers for the three buttons you added.
Q3: How were you able to determine which button was clicked?
- Submit your updated code along with these exercises
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class HelloFrame3 extends JFrame
implements ActionListener {
public final static int X_LOC = 100, Y_LOC = 100,
WIDTH = 300, HEIGHT = 150;
private JButton helloButton;
private JButton exitButton;
public HelloFrame3() {
super("Hello Frame Application");
setDefaultCloseOperation(EXIT_ON_CLOSE);
helloButton = new JButton("Hello");
helloButton.addActionListener(this);
exitButton = new JButton("Exit");
exitButton.addActionListener(this);
JPanel panel = new JPanel();
panel.add(helloButton);
panel.add(exitButton);
Container contentPane = getContentPane();
contentPane.add(panel);
setBounds(X_LOC, Y_LOC, WIDTH, HEIGHT);
setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
Object source = ae.getSource();
if (source == helloButton) {
String msg = "Hey";
JOptionPane.showMessageDialog(this, msg);
} else if (source == exitButton) {
System.out.println("Goodbye!");
System.exit(0);
} else {
System.out.println("Unknown ActionEvent");
}
}
public static void main(String[] args) {
new HelloFrame3();
}
}
^ top
Wrap Up
^ top
Home
| WebCT
| Announcements
| Schedule
| Expectations
| Course info
Help
| FAQ's
| HowTo's
| Links
Last Updated: November 18 2004 @13:56:50
|