Programming and Problem Solving Using Java

Download Report

Transcript Programming and Problem Solving Using Java

Programming
and Problem
Solving Using
Java
Bobby D. Gerardo
Kunsan National University
Summer 2004
Chapter 6
Class Hierarchies,
Inheritance, and Interfaces
Review
3
4
5
6
7
8
Let i=2, j=7
9
10
11
12
Sorting an Array

Method
IntArray.selectionSort(scores)
Sorting method
Reference
13
14
Array Search

Search method
i.e. int index = IntArray.search(scores, 100);
Object
Search method
Array of scores
15
16
17
18
Chapter 6
Class Hierarchies,
Inheritance, and Interfaces
Class Hierarchies, Inheritance, and Interfaces



Throughout the book we followed object oriented
design techniques by using abstraction – modeling real
life entities by retaining only essential information.
We also use encapsulation – clustering data and
methods together into classes, providing safe and
reliable boundaries.
This chapter enhances our capability to use object
oriented design by introducing key features such as
hierarchies, inheritance, and interfaces.
20
Class Hierarchies and Inheritance





Code reuse is very important concept in OOP
If you build new applications using code that
has been written and tested, you are more likely
to develop programs are error free.
Extending the existing class
Subclass with additional data field
Objects also inherit the data fields and methods
of the original class called superclass.
21
Class Hierarchies and Inheritance (cont)


Hierarchies and inheritance is a rich concept that
often appear in science
Inheritance, in combination with hierarchical
organizations, allows you to capture the idea that
one thing maybe a refinement or extension of
another.
22
is a versus has a Relationships

Java allows you to capture both the inheritance (is a)
relationship and the has a relationship. For example,
a car class might be declared as follows:
public class Car extends Vehicle {
Wheels[ ] w = new Wheels[4]; //cars have 4 wheels

The keyword extends specifies that Car is a subclass of
Vehicle.
23
Case Study 1: A Hierarchy
of Employee Classes
Case Study 1: A hierarchy of Employee
Classes
Problem – You have a class called NewEmployee
that stores basic data about an employee: name,
social security number, job title, address, phone
number, age, starting year of employment, and
total pay to date. Besides accessor and modifier
methods, this class has a method to compute
the employee’s numbers of years with the
company, one to compute the number of years
to retirement, and one to update the total pay to
date. It also has a toString() method.
25
Case Study 1: A hierarchy of Employee Classes (cont)

Now suppose you decide to differentiate between
two kinds of employees: salaried and hourly
employees. Hourly employees are paid an hourly
rate and their weekly pay varies depending on how
many hours they work. Salaried employees, on the
other hand, have a fixed annual salary and their
weekly pay rate is the same regardless of how
many hours of work.
26
Analysis and Design

Fig. 6.2 shows a description of class NewEmployee. In addition to
the methods described above, we added an equals() method that
compares two NewEmployee objects.
Fig. 6.2 Class Data Fields
NewEmployee
String name
String socSecNum
String jobTitle
String address
String phoneNumber
int age
int startYear
double totalPay
Methods
….
Attributes
Name
Social security number
Job Title
Address
Phone Number
Age
Starting year of employment
Total pay to date
Behavior
….
27
Implementation


Fig. 6.5 shows the NewEmployee class. The
declaration statements for the type String data
fields initialize them to empty string (“ ”). The
numeric data fields are initialized to zero (the
default value).
See Fig. 6.5 in the book.
28
Testing


Fig. 6.9 (in the book) shows a class that tests all
three employees classes.
Fig. 6.10 (in the book) shows the console
window after the class executes.
29
Operations in Class Hierarchy

Fig. 6.11 shows the class hierarchy for the
employee classes developed in the last section.
Fig. 6.11 Class hierarchy
Object
NewEmployee
SalaryEmployee
HourlyEmployee
30
Operations in Class Hierarchy (2)



Fig. 6.12 Data fields and methods for class
NewEmployee
Fig. 6.13 Data fields and methods for class
SalaryEmployee
Fig. 6.14 Data fields and methods for class
NewEmployeeHourly
31
Operations in Class Hierarchy (3)



Method overloading – When class has multiple
methods with the same name.
A method signature consists of the method
name and its parameter lists
Method overriding – The fact that a method
defined in a subclass blocks the execution of a
method with the same signature defined in its
superclass is called method overriding.
32
Operations in Class Hierarchy (4)






Protected visibility
Shadowing data fields
Misnomer of Superclass and Subclass
Assignment in a Class Hierarchy
Casting in a Class Hierarchy
Passing Objects as Arguments
33
Polymorphism

We will study how we can store objects of
different types in a single array and process them
in a uniform way using a programming language
feature called polymorphism.
34
Polymorphism and Late Binding of
Method Calls


The feature that enables a particular method call
to have behavior at different times is called
polymorphism, which means multiple forms.
The feature that enables a programming
language to select a code fragment to execute at
run-time is called dynamic binding.
35
Case Study 2: A Company
with an Array of Employees
of Different Types
Case Study 2: A Company with an Array
of Employees of Different Types
Problem – In section 5.5, we showed how to
process an array of employees in which each
element was the same type (Employees). Now
our company has several employees of different
types (NewEmployee, HourlyEmployee,
SalaryEmployee). We want to store them in an
array and compute the total company payroll.
37
Interfaces


An interface is used to specify a set of requirements
that is imposed on a collection of classes.
Classes that implement an interface are guaranteed to
have certain functionality (behavior) and also inherit
any constants that are defined in the interface.
Form:
public interface InterfaceName {
abstract method headings
constant declaration
}
38
Declaring Constants

We can declare constants in an interface. These
constants would be inherited by classes that
implement the interface.
public static final double DEDUCT_PCT = 5.5;

In a class Payable to declare DEDUCT_PCT as
a constant with a value of 5.5
39
The Comparable Interface and Method
compareTo



We can declare constants in an interface. One of
these is the Comparable interface, ensures that
the programmer will be able to compare objects
in each class that implements it.
All classes that implement the Comparable
interface must have a compareTo method
See Fig. 6.22 and Table 6.1
40
Abstract Classes

Sometimes we need to new create class, called abstract
class that should be instantiated and whose sole
purpose is to serve as the parent (superclass) of a
group of classes.
Form: public abstract class ClassName {
data field declaration
abstract method headings
method definitions
}
41
Case Study 3: Areas of
Geometric Figures
Case Study 3: Areas of Geometric Figures
Problem – Consider the problem of finding the
total area of a collection of geometric figures.
This problem has many practical applications.
For example in calculating the paint needed for
a house, a painter might visualize the interior
walls as a series of rectangular and triangular
shapes. In calculating the amount of fertilizer to
buy, a landscaper might represent a garden as a
collection of circle and triangular shapes.
43
Case Study 4: Drawing of
Geometric Figures
Case Study 4: Drawing of Geometric Figures
Problem – We would like to draw geometric figures
on the screen. Each figure object will be one of
our standard shapes and can appear anywhere
on the screen with any interior color or border
color.
45
Programming Projects
1.
2.
3.
4.
Prog. Project 1, P. 436
Prog. Project 2, P. 436
Prog. Project 3, P. 436
Prog. Project 4, P. 436
46
☺ End of Chapter