Title: Inheritance
1Inheritance
- Is a used when a new class is defined and
inherits the features of an existing class. - Allows the programmer reuse code that has already
been tested. - The superclass is a more general class the
subclass is a more specific class.
2Inheritance
- Inheritance allows a software developer to derive
a new class from an existing one - The existing class is called the parent class, or
superclass, or base class - The derived class is called the child class or
subclass. - As the name implies, the child inherits
characteristics of the parent - That is, the child class inherits the methods and
data defined for the parent class
3Inheritance
- Inheritance relationships are often shown
graphically in a class diagram, with the arrow
pointing to the parent class
Inheritance should create an is-a relationship,
meaning the child is a more specific version of
the parent
4Deriving Subclasses
- In Java, we use the reserved word extends to
establish an inheritance relationship - class Car extends Vehicle
-
- // class contents
-
5Inheritance Form
- public class SavingsAccount extends BankAccount
- public SavingsAccount (double rate)
- interestRate rate
-
- public void addInterest ()
- double interest getBalance ()
interestRate / 100 - deposit (interest)
-
- private double interestRate
6Controlling Inheritance
- Visibility modifiers determine which class
members get inherited and which do not - Variables and methods declared with public
visibility are inherited, and those with private
visibility are not - But public variables violate our goal of
encapsulation - There is a third visibility modifier that helps
in inheritance situations protected
7The protected Modifier
- The protected visibility modifier allows a member
of a base class to be inherited into the child - But protected visibility provides more
encapsulation than public does - However, protected visibility is not as tightly
encapsulated as private visibility
8The super Reference
- Constructors are not inherited, even though they
have public visibility - Yet we often want to use the parent's constructor
to set up the "parent's part" of the object - The super reference can be used to refer to the
parent class, and is often used to invoke the
parent's constructor
9Single vs. Multiple Inheritance
- Java supports single inheritance, meaning that a
derived class can have only one parent class - Multiple inheritance allows a class to be derived
from two or more classes, inheriting the members
of all parents - Collisions, such as the same variable name in two
parents, have to be resolved - Interfaces gives us aspects of multiple
inheritance without the overhead
10Overriding Methods
- A child class can override the definition of an
inherited method in favor of its own - That is, a child can redefine a method that it
inherits from its parent - The new method must have the same signature as
the parent's method, but can have different code
in the body - The type of the object executing the method
determines which version of the method is invoked
11Method Overriding
class A // Base class fun1() fun2(int
x) // end class A class B extends A //
subclass fun2(int z) fun3() //
end class B
12Overriding Methods
- A parent method can be explicitly invoked using
the super reference - If a method is declared with the final modifier,
it cannot be overridden - The concept of overriding can be applied to data
(called shadowing variables), there is generally
no need for it
13Overloading vs. Overriding
- Overloading deals with multiple methods in the
same class with the same name but different
signatures - Overriding deals with two methods, one in a
parent class and one in a child class, that have
the same signature - Overloading lets you define a similar operation
in different ways for different data - Overriding lets you define a similar operation in
different ways for different object types
14Class Hierarchies
- A child class of one parent can be the parent of
another child, forming class hierarchies
15Class Hierarchies
- Two children of the same parent are called
siblings - Good class design puts all common features as
high in the hierarchy as is reasonable - An inherited member is continually passed down
the line - Class hierarchies often have to be extended and
modified to keep up with changing needs - There is no single class hierarchy that is
appropriate for all situations
16The Object Class
- A class called Object is defined in the java.lang
package of the Java standard class library - All classes are derived from the Object class
- If a class is not explicitly defined to be the
child of an existing class, it is assumed to be
the child of the Object class - The Object class is therefore the ultimate root
of all class hierarchies
17The Object Class
- The Object class contains a few useful methods,
which are inherited by all classes - For example, the toString method is defined in
the Object class - Every time we have defined toString, we have
actually been overriding it - The toString method in the Object class is
defined to return a string that contains the name
of the objects class and a hash value
18The Object Class
- Thats why the println method can call toString
for any object that is passed to it all objects
are guaranteed to have a toString method via
inheritance - The equals method of the Object class determines
if two references are aliases - You may choose to override equals to define
equality in some other way
19Abstract Classes
- An abstract class is a placeholder in a class
hierarchy that represents a generic concept - An abstract class cannot be instantiated
- We use the modifier abstract on the class header
to declare a class as abstract - An abstract class often contains abstract methods
(like an interface does), though it doesnt have
to
20Abstract Classes
- The child of an abstract class must override the
abstract methods of the parent, or it too will be
considered abstract - An abstract method cannot be defined as final
(because it must be overridden) or static
(because it has no definition yet) - The use of abstract classes is a design decision
it helps us establish common elements in a class
that is to general to instantiate
21References and Inheritance
- An object reference can refer to an object of its
class, or to an object of any class related to it
by inheritance - For example, if the Holiday class is used to
derive a child class called Christmas, then a
Holiday reference could actually be used to point
to a Christmas object
22References and Inheritance
Holiday day day new Christmas()
23References and Inheritance
- Assigning a predecessor object to an ancestor
reference is considered to be a widening
conversion, and can be performed by simple
assignment - Assigning an ancestor object to a predecessor
reference can also be done, but it is considered
to be a narrowing conversion and must be done
with a cast - The widening conversion is the most useful
24Polymorphism via Inheritance
- A polymorphic reference is one which can refer to
different types of objects at different times - Inheritance is used as a basis of polymorphism
- An object reference can refer to one object at
one time, then it can be changed to refer to
another object (related by inheritance) at
another time
25Polymorphism via Inheritance
- Suppose the Holiday class has a method called
celebrate, and the Christmas class overrode it - Now consider the following invocation
- day.celebrate()
- If day refers to a Holiday object, it invokes the
Holiday version of celebrate if it refers to a
Christmas object, it invokes the Christmas version
26Polymorphism via Inheritance
- It is the type of the object being referenced,
not the reference type, that determines which
method is invoked - Note that, if an invocation is in a loop, the
exact same line of code could execute different
methods at different times - Polymorphic references are therefore resolved at
run-time, not during compilation
27Polymorphism via Inheritance
- Consider the following class hierarchy
28Polymorphism via Inheritance
- Now consider the task of paying all employees
- Firm
- Staff
- StaffMember
- Volunteer
- Employee
- Executive
- Hourly
29Interface Hierarchies
- Inheritance can be applied to interfaces as well
as classes - One interface can be used as the parent of
another - The child interface inherits all abstract methods
of the parent - A class implementing the child interface must
define all methods from both the parent and child
interfaces
30Subtypes
- Every instance of a subclass is an instance of a
superclass - Every instance of class Male is an instance of
class Human, but not every instance of class
Human is an instance of class Male - The above defines a subtype relation
31Type of an Object Reference
- A variable of an reference type can reference
objects of several types - The rule is substitutability of subtypes
- The type of the object referred to, may have to
be determined at execution time
32Type Conversion - Implicit
- Java allows two kinds of implicit type
conversions - Numeric variables
- Any numeric types can be converted to another
numeric type with larger range, e.g. char gt
int, int gt long, int gt float, float gt
double. - Object reference
- An object reference of class C can be converted
to a reference of a superclass of C.
33Type Conversion --- Explicit Cast
- Numeric variables
- Any numeric types can be explicitly cast to any
other numeric type. May lose bits, precision. - Object reference
- Cast an object reference of a class to a
reference of any other class is - syntactically allowed but
- runtime checked.
34Type Conversion --- Explicit Cast
- Numeric variables
- Any numeric types can be explicitly cast to any
other numeric type. May lose bits, precision. - Object reference
- Cast an object reference of a class to a
reference of any other class is - syntactically allowed but
- runtime checked.
35Cast Object References
class Student ... class Undergraduate
extends Student ... class Graduate extends
Student ... Student student1,
student2 student1 new Undergraduate() //
ok student2 new Graduate() // ok
Graduate student3 student3 student2 //
compilation error student3 (Graduate)
student2 // explicit cast, ok student3
(Graduate) student1 // compilation ok
// run-time exception
36Rule of Assignment
- The type of the expression in the right-hand side
of an assignment must be a subtype of the type of
the variable at the left-hand side of the
assignment - Also known as Polymorphic Assignment
37Polymorphism
- In Java, all instance methods are polymorphic.
- This allows the same computation to work for
object of many shapes, and adapts itself to the
nature of the object.
38Interfaces
- They are used to allow multiple inheritance since
Java forbids full inheritance. - Interfaces are similar to classes but several
restrictions, - Does not have instance variables.
- All methods are abstract, meaning they have name,
parameters, and return type but they dont have
implementations. - All interfaces are automatically public.
39Comparable Interface
- Public class SavingAccount extends BankAccount
- implements Comparable Interfaces are
implemented not extended - . . .
- public int compareTo(Object other)
- //supply implementation
- . . .
-
-
- A class can only have one superclass but they can
have many interface implementations.
40Event Handling
- What is Event Handling ?
- Why do we need Event Handling?
- In most of the programs we have written yet we
asked the users to provide us input in a specific
order. In this case program was in control. - But programs we use everyday do not expect inputs
in a specific order, most of the GUIs today
allow users to provide input in any order they
wish. In this case we say that Users are in
control. - Java provides utilities that enable programs to
react to user commands in any order.
41Event
- What is an Event?
- Whenever user of a graphical program types
characters or uses a mouse any where inside the
window, window manager notifies the program that
an event has occurred. - There are different kinds of events, such as
keyboard events, mouse click events and mouse
move events.
42Event Listener
- We need to differentiate between important and
not so important events, such as we would not be
interested in every move the mouse makes inside
the window. - This is done by installing event listeners that
can distinguish between important and not so
important events. - We use different event listener classes to listen
to different kinds of events.
43Event Source
- To install a event listener we need to know the
source of the event. - Event source is the user interface component that
generates an event. - Some of the examples of event source are a button
is the source for button click event a menu item
is the event source for a menu selection event
and a scrollbar is the source for a scrollbar
adjustment event.
44Event Object
- All the event classes are subclasses of the
EventObject class. The EventObject class has an
important method, getSource that returns the
object that generated the event. - Subclasses have their own methods, such as
MouseEvent class has methods getX and getY that
tell you the position of mouse at the time the
event was generated.
45So how do we use these classes?
- The most complex part of java event handling is
to come up with the listener. - We install a listener by using the
addMouseListener method of the event source which
is an applet in the following example. - Lets see and Example that uses a MouseEvent class
and a MouseListener to trace the mouse events. - In this example the MouseListener provides
various methods such as mouseClicked,
mouseEntered, mouseExited, mousePressed, and
mouseReleased. - Example Spying on Mouse Events.
46Event Adapters
- In the previous example we saw that the
mouseListener interface provided some of the
methods that we might not be interested in
implementing. - Most programs do not care about from where the
mouse entered or exited or if it was presses or
released. We only care about a mouse click like
we did in C. - To use the mouseListener and use just the
mouseClicked method we use MouseAdapters class
which is the part of the java.awt.event package. - Java.awt.event package has adapter class for all
event listener interfaces that have at least two
methods.
47Inner Classes
- We can often install event listeners as inner
classes. - An object of inner class can access the outer
class object that created it, including its
private instance variables. - Here is an example where we draw an Ellipse and
then move it were the user clicked. - Example Move Ellipse
48Frame Windows
- Up to know, all graphical programs that you saw
have been applets, programs that run inside a
browser or the applet viewer. - We can also write graphical applications that
displays output in one or more windows. - The JFrame class implements a top-level window
with a border. - To show a frame, we use JFrame class in the
javax.swing package.
49Frame Window
- JFrame is the fundamental part in the swing
toolkit. - The following example shows how to draw a frame
using the JFrame class - Example Basic Frame.
- Unlike Applets, graphical applications have a
main method.
50Closing Frame Window.
- We must always install a windows listener to
close a frame. - This is required to have the graphical
application exit automatically when the user
closes the frame window.
51Adding User Interface Components to a Frame
- We should not directly draw on a frame window.
This is because drawing directly on the frame
interferes with the display of the user interface
components. - Thus if we want to show graphics on a frame we
simply draw the object on a separate component
and add that component to the frame. - The Swing user interface toolkit provides a
special component called JPanel, just for this
purpose.
52Adding User Interface Components to a Frame
- Drawing on a JPanel is a little different from
drawing on an applet. - To draw on an applet you override the paint
method. To draw on a JPanel, you override the
paintComponent method. - Another difference is when implementing your own
paintComponent, you must call the paintComponent
method of the super class. - If we do not call the super class we would get an
infinite recursive loop.
53Reading Text Input
- Most Graphical programs collect test input
through text field. - To add a text field to a frame we simply create a
JTextField object and add it to the south
location of the content pane. - When a user types in the text field an action
event occurs. - In the following example we let the user type in
the number of ellipses to be displayed. - Example Drawing Ellipses using Text input.
54Arrays
- An array is a collection of data items of same
type. - In java we define arrays as follows
- double data new double 10
- This is the definition of a variable data whose
type is double . That is, data is a reference
to an array of floating-point numbers. The call
new double 10 creates the actual array of 10
numbers. - When an array is first created, all values are
initialized with 0, false or null. - To get some value into the array we must specify
which slot in the array you want to use. - Like C, slots in java are also numbered
starting at 0. -
55Array
- A java array has an instance variable length,
which you can access to find the size of the
array. - for ( int i 0 i lt data.length i )
- note that there are no parentheses after
length - We can copy array variables because they hold
references to the actual array. We can also use - System.arraycopy(from, fromStart, to,
toStart, count) - System.arraycopy(data, 0, newData, 0,
data.length)
56Vectors
- Vector is a container of objects that grows
dynamically. You add new elements using the add
method. - Vectors are objects of a class and not an array,
thus you cannot use the operator to access a
particular slot in the vector. - Instead we use the set method to write an element
and get method to read an element. - Vector product new Vector()
- Product toaster .
- product.set(0 , toaster)
- This stores object toaster in position 0.
- We use the size method to get the size of the
vector. As with arrays, vector positions start at
0.
57Vectors
- Since vectors only hold objects we cannot have a
vector of pure number such as integers, floating
point. - To store numbers in a vector we must use a
wrapper class such as Integer, Double. - We must cast and call the doubleValue method to
get the original floating point number. - Unlike C, element access in Vectors seems to be
more complicated then in Arrays.
58GUI
- Up to now, our graphical programs received user
input from an input dialogue, mouse or text
field. However, graphical applications provides
wide variety of visual gadgets for information
entry such as buttons, menus, scrollbars and so
on. -
59Layout Manager
- You can manage user interface components by
placing them inside containers. Containers can be
placed inside larger containers. Each container
has a layout manager that directs the arrangement
of its components. - Three useful layout managers are border layout,
flow layout, and grid layout. - The content pane of a frame or applet has a
border layout by default. A panel has flow
control layout by default. However you can set
another layout manager instead of the default.
60Buttons
- You construct buttons by supplying string, an
icon or both. - We have to install an actionListener to take some
action when the button is clicked. We can have
the same listener listen to multiple buttons. - To do this we use button references, and not
string labels to identify buttons. - Here is the example that demonstrates this
- Example Single Listener for Multiple Buttons
61Text Component
- We already saw the text fields. But a text fields
hold only one line. If we want to display
multiple lines, we use JTextArea class. - Both JTextField and JTextArea are components of
the JTextComponent class. - If the user hits the enter key in a JTextArea
component, no ActionEvent is generated enter
key just start a new key. - Thus, to find out when the user is done typing we
provide them a button to indicate that they are
finished typing. - Example Using JTextArea component.
-
62Choices
- Now we will see how to present a finite set of
choices to the user. - If the choices are exclusive we use radio
buttons. - In a radio button only one choice can be selected
at one time. - To create radio buttons we first create each
button individually and then add all buttons of
the set to a ButtonGroup object. - We use JRadioButton class to create a radio
button object.
63Choices
- When the choices are not exclusive we use Check
Boxes. - To create an check box object we use the
JCheckBox class. - Unlike radio button objects, we do not put check
boxes inside a button group. - If we have a lot of choices to select from, it is
not viable to use radio buttons because they take
up a lot of space. Another alternative to radio
buttons are combo boxes. - To create a combo box object we use the JComboBox
class. - Example Choices
64Menus
- We can easily create pull down menu in java.
- The container for top-level menu item is called a
menu bar in java. - We create a menu bar object using the JMenuBar
class and adding it to the frame. - Then we add menu using the JMenu class.
- A menu is a collection of menu items or more
menus. - Example Menus.
65Streams
- You use streams to process binary data and
readers and writers for data in text format. - We use FileInputStream, FileOutputStream,
FileReader, and FileWriter objects to access disk
file. - When we are done using the file we must close the
file object. - The basic streams only process one byte at a
time. The basic readers and writers process only
one character at a time. - The PrintWriter can print numbers and strings.
The BufferReader can read whole lines, but you
must still parse their contents.
66Selection Sort
- The selection sort works the same way as in C.
- The order of operation is O (n2).
- Example Selection Sort.
-
67Merge Sort
- Merge Sort is much faster than the selection
sort. - The order of operation of merge sort is O (n
log n). - Example Merge Sort.
68Binary Search
- We use binary search algorithm to search an
element in a data sequence that has been
previously sorted. - The way Binary Search works is we check if the
element we are looking for is in the middle,
first half or second half of the array. We keep
dividing the array till we find or we are left
with list of one element which is not equal to
the element we are looking for. - The order of operation for binary search is
O (log n). - Example Binary Search.
69Recursion
- When we call the same function again and again
till certain condition is met and we return the
result. - Recursion are not always efficient. It depends on
what we are using it for. - In an example that calculates fibonacci we see
that the recursion takes very long because it
computes the same number again and again. - An alternative to this particular problem is
using a loop rather then recursion.
70Intro to Data Structure
- Sometimes we need to add or remove a record from
a list of hundred elements. If we use an array to
store such a list we have to move a lot of record
to insert or remove an element. - An efficient alternative to this is the use of
Linked List. - Linked list allows us to easily remove or insert
elements in the list. - We use the LinkedList class in the java.util to
create a linked list object. - We cannot access elements in the list directly
like we did in arrays and vectors. - Just like C we use Iterators to traverse
through the linked list and reference to the
links.
71Linked List
- We create list iterator object using the
ListIterator class. - We move the iterator object using the next
method. - The hasNext method returns true if there is next
element in the list and also increments the
iterator to the next position. - This is different from C were we have to first
check the next element and then increment the
iterator in two different statements. - We can also use the previous and hasPrevious
methods to traverse through the list backwards. - Add method adds an object at the end of the list.
- Example Linked List.
72Implementing Linked List
- Just like C we can also implement our own
linked list. We do not have to use the standard
container. - Example Linked List 2.
73Binary Search Trees
- Tree structures can significantly speed up the
storage and retrieval of sorted data. - The simplest of such trees structures is the
binary search tree. - A Binary search tree is a self organizing data
structure. You insert elements into the tree, not
into particular position. The insertion algorithm
finds an appropriate position for the new
elements. - Example Trees.