ICT167 Topic08
ICT167 Topic08
Inheritance and
Introduction to
Event-driven
Programming
ICT167 Principles of
Computer Science
3
Objectives
§ Define inheritance and polymorphism
§ Be able to give examples of uses of
inheritance
§ Be able to use the correct terminology for
inheritance (base class and derived class)
§ Understand inheritance between Java
classes
§ Explain the concept of overriding of
methods
§ Distinguish between overriding and
overloading
4
Objectives
§ Explain the use of the term super in a
constructor
§ Understand a class hierarchy
§ Know that a derived class object can have a
super class reference
§ Be able to define and use derived classes
in Java
§ Understand the concept of multiple
inheritance
§ Understand Java interfaces
5
Objectives
§ Understand the basics of event-driven
programming
§ Explain the term GUI
§ Give a brief description of the Java Swing
event-driven programming
§ Be able to determine and explain the
behaviour of simple Java GUI programs
Reading Savitch: Chapters 8.1, 8.2, 8.3 and
Chapter 13 (see textbook website)
6
Inheritance
§ Inheritance enables us to define a new class
based on a (general) class that already
exists
§ The new class will be similar to the existing
class, it will be able to use all the facilities of
the existing class, but will have some new
characteristics
§ This makes programming easier, because
you can build upon your previous work
instead of starting out from scratch
7
Inheritance
Inheritance
Inheritance
Terminology
Terminology
Terminology
// set method
public void setName(String newName) {
name = newName;
}
public void writeOutput(){ // output method
System.out.println("Name: " + name);
}
// equal method
public boolean sameName(Person otherPerson) {
return (this.name.equalsIgnoreCase(
otherPerson.name));
}
} // end class Person
15
// Another constructor
public Student(String initialName,
int initialStudentNumber) {
// call to other constructor of super class Person
super(initialName);
studentNumber = initialStudentNumber;
}
public void reset(String newName,
int newStudentNumber) {
// call to the super class method
setName(newName);
studentNumber = newStudentNumber;
}
17
Example: Output
/* OUTPUT
Name: No name yet.
Student Number : 0
Name: Jason Bourne
Student Number : 12345678
Name: James Bond
Student Number: 7
Not Same
*/
22
Class Hierarchies
Figure 8.1 A class hierarchy
UML Inheritance Diagrams
• Figure 8.2 A class
hierarchy in
UML notation
UML Inheritance Diagrams
• Figure 8.3
Some details
of UML class
hierarchy
from
figure 8.2
39
Class Hierarchies
40
Using Inheritance
§ The diagram on the previous slide shows a
hierarchy of classes
§ In this class hierarchy, many methods and
instance variables may be inherited
downwards from super class to derived
class
§ Java supports this easily
§ In a hierarchy, each class has at most one
base class (super or parent), but can have
several derived (sub or child) classes
41
Using Inheritance
Using Inheritance
§ Eg:
Date today = new Date();
Employee emp = new Employee();
emp = userChooseEmployee();
System.out.println(“You have chosen to retire
the following employee”);
emp.writeName();
System.out.println(“Are you sure(yes/no)?”);
Scanner kb = new Scanner (System.in);
String reply = kb.next();
43
Using Inheritance
if (reply.equals(“yes”)){
emp.FinalizeRecords(today);
} else {
System.out.println(“Request ignored.”);
}
System.out.println(“End of this request.”);
people[1] = new
Undergraduate("Cotty, Manny",
8812, 1);
Polymorphism
• Given:
Person[] people = new Person[4];
people[0] = new Student("DeBanque, Robin",
8812);
• When invoking:
people[0].writeOutput();
• Which writeOutput() is invoked, the one defined
for Student or the one defined for Person?
• Answer: The one defined for Student
An Inheritance as a Type
• The method can substitute one object for
another
– Called polymorphism
• This is made possible by mechanism
– Dynamic binding
– Also known as late binding
Dynamic Binding and Inheritance
Multiple Inheritance
§ Occasionally, the natural description of a
problem suggests a different form of
inheritance, not like an upside down tree
§ For example, a postgraduate tutor may be both
a staff member and a student
§ We may need methods to deal with paying them
for taking lab classes, and methods for dealing
with their student number, HECS fees and unit
results
§ We want to inherit these methods from different
super classes
§ This is called multiple inheritance
53
Multiple Inheritance
54
Java Interfaces
Java Interfaces
§ Java does not allow multiple inheritance
except in a very special case:
§ One of the super classes must be an interface,
which is like a class with methods with no
bodies. (Do not confuse two uses of the word in
this topic)
§ A Java interface is a collection of constants
and method declarations
§ The method declarations do not include an
implementation (i.e. there is no method body)
56
Java Interfaces
§ A derived class that extends a base class
can also implement an interface to gain
some additional behaviour
§ An interface definition has the following
general form:
// File: InterfaceName.java
public interface InterfaceName {
constant definitions
method declarations (without
implementations)
}
57
Java Interfaces
§ A class definition then implements an
interface as follows:
public class SomeClass extends
SomeParent implements
InterfaceName
{
// body of the class SomeClass
}
§ You will know that an interface is involved if
you see the word implements which is used
instead of extends for interfaces
58
Java Interfaces
§ Eg:
public class ButtonDemo extends JFrame
implements ActionListener
GUI Components
§ The GUI components are – windows,
labels, text fields or text areas, buttons, etc.
§ The components (labels, text areas/text
fields and buttons) are added to the content
pane (the area below the title bar and
inside border) of a window and not to the
window itself
§ All GUI components are objects in Java
and therefore are instances of a particular
class type
73
GUI Components
GUI Components
Windows
Windows
§ Some methods provided by the JFrame
class:
§ JFrame(String title)
§Constructor for creating a JFrame with a title
§ Container getContentPane()
§Returns the content pane of the JFrame, which has
the add method for adding components
§ void setSize(int width, int height)
§Method to set the size of the window
§Eg: myWindow.setSize(500, 300);
§ void setTitle(String title)
§Method to set the title of the window
77
Windows
§ Some methods provided by the JFrame class:
§ void setVisible(boolean b)
§Method to display window in the program
§Displays window on the screen if b is true
§ public void addWindowListener(WindowEvent e)
§Method to register a window listener object to a
Jframe
§ public void setDefaultCloseOperation (int operation)
§Method to determine action to be taken when the
user clicks on window closing button, x, to close the
window
§Eg:
setDefaultCloseOperation(EXIT_ON_CLOSE)
;
78
Windows
Windows
Windows
§ Alternatively:
§ Create the class containing the application
program by extending definition of class
JFrame using inheritance
§ The new class can use features such as
methods it inherits from the existing class
(JFrame), and can add some functionality of it
own
81
Control Pane
Control Pane
§ Eg:
Container c1;
c1 = getContentPane();
§ or,
Container c1 = getContentPane();
§ In order to design the layout to decide where
to place the GUI components in the content
pane, the class Container provides the
method setLayout
83
Control Pane
§ The components can be added/attached to
the content pane by using method add of the
Container class
§ The class Container is contained in the
package java.awt
§ To use this class in your program, you need
to include either the statement:
import java.awt.*;
§ or
import java.awt.Container;
84
Labels
§ A label is a special kind of text that can be
added to a JFrame (or to any of a number of
other kinds of objects)
§ It provides instruction or information on a
GUI
§ It displays a single line of read-only text, an
image or a mixture of both
§ Labels are created by instantiating objects
of class Jlabel (which is contained in the
package java.swing)
85
Labels
§ Eg: Give a string as an argument to the
constructor for the JLabel class:
JLabel label1;
label1 = new JLabel(“Please don’t
click that button!”);
c1.add(label1,BorderLayout.CENTER);
§ Eg: set string describing label2 as right-
justified
JLabel label2;
label2 = new JLabel(“Enter your
name:”,
SwingConstants.RIGHT);
86
JTextField mytext;
mytext = new JTextField(50);
§ This statement instantiates the object
mytext and sets the width of this text field to
50 characters
§ The object mytext will be added to the
content pane using the add method of
Container class
88
Buttons
Buttons
§ Some methods provided by the class
JButton:
§ public JButton(String str)
§Constructor to initialise the object to text specified
by str
§ public void setText(String str)
§method to set text of the button to string specified
by str
§ public String getText()
§method to return the text contained in button
§ public void addActionListener(ActionListener e)
§method to register a listener object to the button
object
93
Layout Managers
§ Layout Managers are objects that decides
how components will be arranged in a
container
§ Some types of layout managers:
§ BorderLayout
§ FlowLayout
§ GridLayout
§ Each type of layout manager has rules about
how to rearrange components when the size
or shape of the container changes
94
BorderLayout.SOUTH
c1.setLayout(new BorderLayout());
. . .
c1.add(label1, BorderLayout.NORTH);
95
Handling an Event
§ When button (JButton) is clicked, an event
is created – called action event
§ Action event sends a signal to another
object, known as action listener
§ When the listener receives the message, it
performs some action
§ Sending a message or an event to a listener
simply means that some method (eg,
actionedPerformed) in the listener object is
invoked with the event as the argument
99
Handling an Event
§ This invocation happens automatically –
there is no code corresponding to the
method call
§ However, you must specify two things:
§ For each JButton, you must specify a
corresponding listener object – called
registering the listener
§ You must define the methods that will be called
when the event is fired (i.e., sent to the listener)
§ Java does not allow us to instantiate an
object of type ActionListener
100
Class ActionListener
§ The class ActionListener (part of the
package java.awt.event) handles action
events
§ It is a special type of class called an
interface and contains the method
actionPerformed
§ An interface is a class that only contains the
method headings (terminated with a
semicolon) and not their
definitions/implementations
§ Java does not allow us to instantiate an
object of type ActionListener
101
Class ActionListener
§ One way to register an event is to create a
class on top of ActionListener so that the
required object can be instantiated
§ Eg:
private class MyButtonHandler implements
ActionListener {
public void actionedPerformed
(ActionEvent e){
//Code for tasks to be performed go here
}// end actionedPerformed
}// end class MyButtonHandler
102
Example: SimpleApp
//SimplApp.java - a simple example of a GUI program
//You should be able to give a brief description of what
//such a program will do and the steps involved
import javax.swing.*; //for JFrame, JButton, JLabel
import java.awt.*; //for Container, BorderLayout
import java.awt.event.*; //for WindowAdapter,
ActionListner, ActionEvent
public class SimplApp extends JFrame {
// define window's width and height in pixels
private static final int WIDTH = 400;
private static final int HEIGHT = 200;
103
Example: SimpleApp
Example: SimpleApp
Example: SimpleApp
// Below is the constructor for the class SimplApp
public SimplApp(String windowTitle) {
super(windowTitle);
setSize(WIDTH, HEIGHT);
// create content pane to add components to
window
Container c1 = getContentPane();
c1.setLayout( new BorderLayout());
// create a label component with the String
centred
infoLabel = new JLabel( "Initial",
JLabel.CENTER);
c1.add( infoLabel, BorderLayout.CENTER);
106
Example: SimpleApp
// create a button component
JButton button1=new JButton("Don't Press
Me!");
c1.add( button1, BorderLayout.NORTH);
//goes at top
// add an action event to button
ButtonAction myAction = new ButtonAction();
button1.addActionListener(myAction);
// add action event to window close button
WindowDestroyer myListener = new
WindowDestroyer();
addWindowListener( myListener);
} //end of SimplApp constructor
107
Example: SimpleApp
Example: BinarySearch
Example: BinarySearch
Example: BinarySearch
Example: BinarySearch
Example: BinarySearch
Example: BinarySearch
Example: BinarySearch
Example: BinarySearch
if ( index != -1 )
resultField.setText("Value found at
index " + index);
else
resultField.setText("Value not found");
}//end of actionPerformed method
116
Example: BinarySearch
Example: BinarySearch
Example: BinarySearch
Example: BinarySearch