Object-Oriented Programming (721112) - Philadelphia

Preview:

Citation preview

Object Oriented Paradigms by Dr. Nadia Y. Yousif

1

Object-Oriented Programming (721112)

A Core Module for Students in

CS, CIS, SE, ACS Departments

Faculty of IT / Philadelphia University

Second Semester 2006/2007

A-P

DF

ME

RG

ER

DE

MO

Object Oriented Paradigms by Dr. Nadia Y. Yousif

2

Object-Oriented Programming (721112)

Lecturer: Dr. Nadia Y. Yousif

Email: nyaaqob@philadelphia.edu.jonadiayy@hotmail.com

Room: IT 332

Object Oriented Paradigms by Dr. Nadia Y. Yousif

3

Course Outline

• Aims• Objectives• Assessment and Passing the Subject• Lectures and Practice Classes• Lecturer and Consultation• Recommended Reading• Course Overview • Chapter 1

Object Oriented Paradigms by Dr. Nadia Y. Yousif

4

Aims of this module

• To develop an understanding of the principles of the object-oriented paradigm.

• To provide familiarity with approaches to object-oriented modeling and design.

• To provide a familiarity with the syntax, class hierarchy, environment and simple application construction for an object-oriented programming language.

Object Oriented Paradigms by Dr. Nadia Y. Yousif

5

Course Objectives• Acquire a full Object Oriented Thinking.• Have a clear understanding of the object-oriented

concepts such as objects, classes, inheritance, and polymorphism.

• Have an informal understanding of the operational semantics of object-oriented programs in terms of creation of objects and messages passing between them.

• Be able to design small object oriented programs which meet requirements expressed in English, with a strong software engineering foundation

• Have knowledge of Object Oriented Design guidelines.• Be able to code small programs in Java language.• Be able to produce and maintain large, high-quality

software systems

Object Oriented Paradigms by Dr. Nadia Y. Yousif

6

Assessment and Passing

• There are three assessment components:- Two midterm exams worth 15% of the marks

each- Course work worth 20% of the marks- Final exam worth 50%

• You need to achieve an overall mark of 50% to pass the course.

Object Oriented Paradigms by Dr. Nadia Y. Yousif

7

Lectures and Practice Classes

• Lectures will be held at:11:15 am on Monday and Wednesday in Lab 7501There will be one practice class each week:12:45 pm to 13:45 pm on Wednesday, Lab 7501

During the first three weeks, tutorials will be given in the practice class,

• During the rest weeks, students are expected to work on practice problems, or on their assignments

• The lecturer will be available to comment on, and help with, solutions during the practice class.

Object Oriented Paradigms by Dr. Nadia Y. Yousif

8

Lecturer and Consultation

• Lecturer:Dr. Nadia Y. YousifFaulty of IT, Room 332, Phone Ext: 2544email: nyaaqob@philadelphia.edu.jo

• Consultation– The primary time for consultation is during the

practice classes– Other consultation at the office hours (in room

332) on:(Sun, Tues, Thu) 13:00 – 14:00 (Mod, Wed) 13:45 – 15:15

Object Oriented Paradigms by Dr. Nadia Y. Yousif

9

Recommended Reading

• The text book is:David J. Barnes and Michael Kolling,Objects First with Java: A Practical Introductionusing BlueJ, Prentice Hall, 2003

Note:Most of the slides of this module are from the above

reference

Object Oriented Paradigms by Dr. Nadia Y. Yousif

10

Lab and BlueJ

• In the lab hours, we will implement java program by using the Java Development Environment (BlueJ) that runs on top of Sun Microsystems's Java Development Kit.

Object Oriented Paradigms by Dr. Nadia Y. Yousif

11

Course Overview

• Overview• Objects and classes• Understanding class definitions• Object interaction• More sophisticated behaviour - libraries• Well-behaved objects - testing, maintaining, debugging• Designing classes• Inheritance• Polymorphism• Extendable, flexible class structures• Handling errors• Grouping objects• Designing applications

Object Oriented Paradigms by Dr. Nadia Y. Yousif

12

Overview

Topics to cover:- Structured Programming Paradigm (SPP)- Object-Oriented Paradigm (OOP)- Paradigm Shift from (SPP to OOP)- What is this OO thing?

Object Oriented Paradigms by Dr. Nadia Y. Yousif

13

Structured Programming Paradigm (SPP)

• Top Down – Step wise refinement• Solves all of problem in one program• Break down into hierarchy of modules

1. INITIALISE2. MAIN PROCESS A

2.1 PROCEDURE-A2.2 PROCEDURE-B

2.2.1 Function A2.2.2 Procedure B

Function B1Subroutine B2

65. FINALISE

Object Oriented Paradigms by Dr. Nadia Y. Yousif

14

Object-Oriented Paradigm (OOP)

Objects – real world thingsArrows – messages for tasks and activities

Window

Enrolment

Icon

DB Connection

Button

Student Application

Network Socket

Authorised Clerk

TextArea

Student

Object Oriented Paradigms by Dr. Nadia Y. Yousif

15

Paradigm Shift from (SPP to OOP)

• Real World DATA first• Not processing first

– In real world, algorithms and processes change– Underlying data objects remain stable

• Intended benefits– Solve the “software” crisis– Break complexity into small manageable chunks– Make software maintenance easier– Allow reuse of components – plug and play

Object Oriented Paradigms by Dr. Nadia Y. Yousif

16

What is this OO thing?

• The world consists of "objects" and we are trying tosolve real world problems - hence we should useobjects to model and hopefully solve some of theproblems.

• Object Oriented Software Engineering Paradigm - setof techniques and processes focusing on how toanalyse and model a real world problem and todesign a solution.

• Object Oriented Programming Language - aprogramming language which supports theimplementation of an object oriented model - we willuse Java.

Object Oriented Paradigms by Dr. Nadia Y. Yousif

17

The Promise

• Allows us to build better software systems cheaper by– breaking complexity into small manageable chunks– make software maintenance easier– allow to reuse software pieces

• Does it work in real life? Sort of. Not perfectly, but much better than any other approach so far.

Object Oriented Paradigms by Dr. Nadia Y. Yousif

18

Chapter 1: Objects and ClassesTopics to cover:• Objects and Classes

- Objects; Classes- Describing the Objects- Finding Generalizations and Associations- Behavior- Class Design Hints- Good Programming Style- Object Communication- Methods and Parameters- Method Invocation- State of the Object- Source Code of the Class

Object Oriented Paradigms by Dr. Nadia Y. Yousif

19

Chapter 1: Objects and Classes (Cont.)

Objects• Objects represent ‘things’ from the real world, or from some problem domain (example: “the red car down there in the car park”)

• Any "thing" can be an object.• physical things (chair, car, ...)• occurrences (meeting, date, ...)• …• Rule of thumb: If you can describe the "thing" using an English noun, it could be an object.

• Each object is unique.

Object Oriented Paradigms by Dr. Nadia Y. Yousif

20

Objects

• We can think of an object as a collection of- variables (or attributes) i.e. stuff the object "knows“- operations (or behaviors) i.e. stuff the object "does”

• This is a mechanism for encapsulation. This provides- modularity- information hiding

• Object’s operations (Java calls them methods) can be invoked (or called)

Object Oriented Paradigms by Dr. Nadia Y. Yousif

21

Classes• A class describes – in an abstract way - all objects of a

particular kind (example: “Car”)

• NOTE:– You should choose meaningful names for classes and

methods that express the required task– Names of classes start with capital letter (e.g. Circle)– Names of objects start with lowercase letters (e.g. circle_1)– Name of variables (or fields) start with lowercase letters

(e.g get, print)– If name is longer than one word, capitalize first letter of

each word except the first, e.g.– for a class: ShortPureBredDogs– for a method: takeDogForWalk

Object Oriented Paradigms by Dr. Nadia Y. Yousif

22

Classes (Cont.)

• A class describes an object - think of it as a blueprint. A class defines:- the attributes- the behavior- how to construct (usually)- how to destruct (if necessary)- a particular type of object.

• A class is NOT an object.- You can use a class to create object of this class.- An object is called instance of the class it was createdfrom.

- The object is of type of this class.

Object Oriented Paradigms by Dr. Nadia Y. Yousif

23

Example of Class vs. Object

• A blueprint (class) of a Car tells you– the attributes (number of wheels, color, number of gears, ...)– the behavior (accelerate, brake, turning, ...)– how to construct one (1. Take a large sheet of metal andbend it 2. ...)

– how to destruct one (Take it to the wreckers)

• IMPORTANT: A class is NOT an object.• It is hard to drive around with the blueprint, but you could use

it to build one or more cars.

Object Oriented Paradigms by Dr. Nadia Y. Yousif

24

Our World In This Lecture

• In this lecture we will use object orientation to think about all our "Contacts".

• Contacts are all persons we interact with in some way. We give them phone calls, we meet them, we write them email, letters, faxes. We also "in contact“with non-persons - companies, student groups, ...

• So what's the program supposed to do? There is no program. The idea is think about these objects, about their attributes and behavior. At the end, we might think about what the objects we put together could be used for.

Object Oriented Paradigms by Dr. Nadia Y. Yousif

25

Object Candidates

• Person - Ahmed, Ali, Saba, ...• Companies, Student Organizations• Email, Fax, Letter, Phone Calls• Meetings• Relationships (marriage, partner, employee, boss,

friend, ...)• ...

Object Oriented Paradigms by Dr. Nadia Y. Yousif

26

Describing The Objects (Classes)

• What are the attributes of a person?- Name - Birthday- Address - Length - ...

• What are the attributes of a company?- Name - Address- Task - …

• What are the attributes of a student organization?- …

Object Oriented Paradigms by Dr. Nadia Y. Yousif

27

Finding Generalizations and Associations

• What's common between persons, companies, student organizations?

• How can we generalize, so we don't have to repeat ourselves when describing each of the ones above?

• Which objects are "related"?- Person to Person- Person to Organization- Organization to Organization

• Associations can have different cardinalities.

Object Oriented Paradigms by Dr. Nadia Y. Yousif

28

Behavior

• What can the different objects do?• Person: Say name• Organization: Move• Person: getJob. looseJob• Organization: goBankrupt• What could be the sequence of message passing in

goBankrupt be?

Object Oriented Paradigms by Dr. Nadia Y. Yousif

29

Less Obvious Objects

• Is a meeting an object?• Does it have attributes?• Does it have "behavior"?

• Meeting can be a object:- Attributes: Date, Time, Location, ...- Behavior: Schedule, Cancel, ...- Relationship: Attendees- Generalization: Encounter

Object Oriented Paradigms by Dr. Nadia Y. Yousif

30

A Closer Look at Address Attribute

• What is an address?- Street, State, Postcode, City, ...

• We may expand our Person class ...• And what is a location in our meeting class?• Address is an object by itself!• Attributes?• Behaviour?• Now an organization can have multiple addresses!

Object Oriented Paradigms by Dr. Nadia Y. Yousif

31

Creating An Address Book For All Your Contacts

• Now you want to write down the addresses of all your contacts.

• You also want to include the birthdays of all your contacts.• We need a behavior on all contacts which talks about them.• Persons should give their name, address and birthday.• Companies should give their name and address.• We don't want to specify how to give name and address twice -

what's a better way?• Note that giveDetails( ) does different things in different

subclasses even though the interface is the same - when a message is sent, the type of object it is sent to determine,which behavior is invoked. This is called polymorphism

Object Oriented Paradigms by Dr. Nadia Y. Yousif

32

Discovering Classes

• Noun phrase approach• “Object Think”• Hybrids

Object Oriented Paradigms by Dr. Nadia Y. Yousif

33

Noun Phrase Approach• Assume well specified requirements/problem specification

document• Look for noun phrases - each noun is candidate class• Group

– relevant classes– fuzzy classes– irrelevant classes

• Discard synonyms. Refine until list includes only relevant classes

• Use this as basis• More will be discovered during design process• Bottom up approach that assumes requirement document is

complete and correct• Is this true in reality ?

Object Oriented Paradigms by Dr. Nadia Y. Yousif

34

Object Think

• The Object-Oriented Approach, • Purpose is to change way developers think

about computer systems from whole approachto one object at a time

• Let object speak for itself• Let object speak for itself in context of

application

Object Oriented Paradigms by Dr. Nadia Y. Yousif

35

Example

• I am a button on the screen– I know what window I am attached to– .. my position– .. my height and width– .. my background color– .. what the label says– .. what to do when clicked

• I am a window– I know my title– ……– I Know what objects are attached to me– … how to move– … how to shrink– … how to close myself

Object Oriented Paradigms by Dr. Nadia Y. Yousif

36

In context of application

• I am actually a rock– I don’t know anything– I don’t know how to do anything

• I am a rock in context of a rock collector– I know my type, weight, shape, color, density and value– I know who discovered me– … where I was found– … how I was foundAnd– I can tell people about myself– I can add myself to a collection (and remove myself)– I can associate myself with a shelf

Object Oriented Paradigms by Dr. Nadia Y. Yousif

37

To Do

• Think in terms of objects for people and transportation - think at least about persons, cars, bikes and locations.

• So, this is all totally easy and a waste of time for you? Great, you'll make a lot of many as a star OO Analyst and Designer ...

Object Oriented Paradigms by Dr. Nadia Y. Yousif

38

Class Design Hints• Always keep data private• Always initialize data

- don’t rely on defaults• Do not use too many primitive types

- if needed, introduce a new class- e.g. Address instead of street, city, state and zip

• Not all fields need individual accessors and mututors (discussed later)

- e.g. setDate not setDay, setMonth, setYear• Use consistent form for class definitions

- attributes - constants - constructors - methods - static- public - package scope - private

• Break up classes with too many responsibilities• Make names reflect responsibilities

Object Oriented Paradigms by Dr. Nadia Y. Yousif

39

Program Documentation

• Programs are often the only form of system documentation !

• Use comments• Use comments to describe purpose• Use comments to clarify difficult concepts• Write self-documenting code using good

programming styles

Object Oriented Paradigms by Dr. Nadia Y. Yousif

40

Good Programming Style

• Use blank lines, space characters, etc for readability• Java - use naming conventions

– ClassName– objectIdentifier– methodName– for widgets use prefixes lbl txt btn

• Use aligned braces (use comments at ends of blocks)• Use indentations• Use spacing (e.g. in lists, expressions)• Meaningful variable names• Split long statements meaningfully

Object Oriented Paradigms by Dr. Nadia Y. Yousif

41

Object Communication

• Messages- Object communicate via message passing.- A message consists of an object (the recipient), a

method, and optional parameters.• Example

An object: point1– Attributes or fields: int x, y;– Method: void move (int dx, int dy)– A message: point1.move(10, 10)

Object Oriented Paradigms by Dr. Nadia Y. Yousif

42

Methods and Parameters

– Methods may have parameters of different types to pass additional information needed to execute

– A type specifies what kind of data can be passed to a parameter.

– Methods may return a result via a return value

Object Oriented Paradigms by Dr. Nadia Y. Yousif

43

Methods and Parameters (Cont.)

– Method Signature provides information about the method:- its name- type of its returned result (or void if no returned result)- list of parameters

– Examplesint method1 ( )

void moveHorizontal (int distance)

methodmethod (no parameter)(no parameter)Type of Type of resultresult

(parameter)(parameter)methodmethodNo returned resultNo returned result

Object Oriented Paradigms by Dr. Nadia Y. Yousif

44

Methods Invocation

• Methods are invoked by objects using the dot notation.

e.g.circle_1.moveHorizontal (50)

This means that object circle_1 invokes methodmoveHorizontal with 50 as parameter

Object Oriented Paradigms by Dr. Nadia Y. Yousif

45

Methods Invocation (Cont.)

• The called method could be within the same class, in which case only the method name is needed

myMethod();

myMethodcompute

Object Oriented Paradigms by Dr. Nadia Y. Yousif

46

Methods Invocation (Cont.)

• The called method could be part of another class or object

obj.doIt( );

main doIt helpMe

helpMe();

Object Oriented Paradigms by Dr. Nadia Y. Yousif

47

Other observations

• many instances can be created from a single class• an object has:

- attributes: values stored in fields (the state of the object).- behaviors (or methods) - what it can do (or be done to it)

• the class defines what fields an object has, but each object stores its own set of values (the state of the object)

• For example, consider a Circle class that has diameter as a field

• The state of the object circle_1 is its current diameter• The behavior of circle_1 is that it can be enlarged by

increasing its diameter• Note that the behavior of the circle object might change its

state

Object Oriented Paradigms by Dr. Nadia Y. Yousif

48

State

Object Oriented Paradigms by Dr. Nadia Y. Yousif

49

Two Circle Objects

Object Oriented Paradigms by Dr. Nadia Y. Yousif

50

Source Code

• Each class has source code (Java code) associated with it that defines its details (fields and methods).

int x, y;char ch; Field declarations

Method declarations

Object-Oriented Paradigms 1

Chapter 2Understanding Class Definitions

Main concepts to be covered:• fields• constructors• methods• parameters• assignment statements• conditional statements

Object-Oriented Paradigms 2

Ticket Machines – an External View

• Exploring the behavior of a typical ticket machine.– Use the naive-ticket-machine project.– Machines supply tickets of a fixed price.

• How is that price determined?

– How is ‘money’ entered into a machine?– How does a machine keep track of the money

that is entered?

Object-Oriented Paradigms 3

Ticket Machines – an External View (Cont.)

• Interacting with an object gives us clues about its behavior.

• Looking inside allows us to determine how that behavior is provided or implemented.

• All Java classes have a similar-looking internal view.

Object-Oriented Paradigms 4

Basic Class Structure

The outer wrapperof TicketMachine

public class TicketMachine{

Inner part of the class omitted.}

public class ClassName{

FieldsConstructorsMethods

}

The contents of aclass

Object-Oriented Paradigms 5

Fields• Fields store values for an object.• They are also known as instance variables.• Use the Inspect option to view an object’s fields.• Fields define the state of an object.public class TicketMachine{ private int price;

private int balance;private int total;

Constructor and methods omitted.}

private int price;

visibility modifier type variable name

Object-Oriented Paradigms 6

Constructors• Constructors initialize an object.• They have the same name as their class.• They store initial values into the fields.• They often receive external parameter values for this.

public TicketMachine (int ticketCost){

price = ticketCost;balance = 0;total = 0;

}

Object-Oriented Paradigms 7

Passing Data via Parameters

Object-Oriented Paradigms 8

Assignment

• Values are stored into fields (and other variables) via assignment statements:

variable = expression;e.g. price = ticketCost;

• A variable stores a single value, so any previous value is lost.

Object-Oriented Paradigms 9

Accessor Methods

• Methods implement the behavior of objects.• Accessors provide information about an

object.• Methods have a structure consisting of a

header and a body.• The header defines the method’s signature.

public int getPrice()• The body encloses the method’s statements.

Object-Oriented Paradigms 10

Accessor Methods

public int getPrice( ){

return price;}

visibility modifierreturn type

method name

parameter list (empty)

return statement

start and end of method body (block)

Object-Oriented Paradigms 11

Mutator Methods

• Have a similar method structure: header and body.

• Used to mutate (i.e., change) an object’s state.

• Achieved through changing the value of one or more fields.– Typically contain assignment statements.– Typically receive parameters.

Object-Oriented Paradigms 12

Mutator Methods

public void insertMoney (int amount){

balance += amount;}

visibility modifier return type (void)method name parameter

assignment statement

field being changed

Object-Oriented Paradigms 13

Printing from Methodspublic void printTicket(){ // Simulate the printing of a ticket.

System.out.println("##################");System.out.println("# The BlueJ Line");System.out.println("# Ticket");System.out.println("# " + price + " cents.");System.out.println("##################");System.out.println();

// Update the total collected with the balance.total += balance;// Clear the balance.balance = 0;

}

Object-Oriented Paradigms 14

Reflecting on the Design of the Ticket Machines

• Their behavior is inadequate in several ways:– No checks on the amounts entered.– No refunds.– No checks for a sensible initialization.

• How can we do better?– We need more sophisticated behavior.

Object-Oriented Paradigms 15

Making choices

public void insertMoney(int amount){ if(amount > 0)

{balance += amount;

}else{ System.out.println("Use a positive amount: "

+ amount);}

}

Object-Oriented Paradigms 16

Making choices

if(perform some test) {Do the statements here if the test gave a true result

}else {

Do the statements here if the test gave a false result}

‘if’ keyword boolean condition to be tested - gives a true or false result

actions if condition is true

actions if condition is false‘else’ keyword

Object-Oriented Paradigms 17

Local variables

• Fields are one sort of variables.– They store values through the life of an object.– They are accessible throughout the class.

• Methods can include shorter-lived variables.– They exist only as long as the method is being

executed.– They are only accessible from within the

method.

Object-Oriented Paradigms 18

Local variables

public int refundBalance(){

int amountToRefund;amountToRefund = balance;balance = 0;return amountToRefund;

}

A local variable

No visibilitymodifier

Object-Oriented Paradigms 19

Review• Class bodies contain fields, constructors and methods.• Fields store values that determine an object’s state.• Constructors initialize objects.• Methods implement the behavior of objects.• Fields, parameters and local variables are all variables.• Fields persist for the lifetime of an object.• Parameters are used to receive values into a constructor or

method.• Local variables are used for short-lived temporary storage. • Objects can make decisions via conditional (if) statements.• A true or false test allows one of two alternative courses of

actions to be taken.

Object-Oriented Paradigms 1

Chapter 3Object interaction

Creating cooperating objectsTopics to Cover• An Example: A Digital Clock to demonstrates:

- Abstraction and Modularization- Object Diagram- Class Diagram- Primitive Types and Composite Types- Objects Creating Objects- Method Calling- Internal Methods

Object-Oriented Paradigms 2

An Example: A Digital Clock

• In this chapter, a digital clock is considered • Digital clock is as follows:

Object-Oriented Paradigms 3

Abstraction and Modularization

• Abstraction is the ability to ignore details of parts to focus attention on a higher level of a problem.

• Abstraction is also considered as a modelof a complex system that includes only the details essential to the perspective of the viewer of the system.

• For example Programs are abstractions.

Object-Oriented Paradigms 4

Abstraction and Modularization (Cont.)

• Example: A car is viewed by two different ways

Object-Oriented Paradigms 5

Abstraction and Modularization (Cont.)

• Modularization is the process of dividing a whole thing into well-defined parts, which can be built and examined separately, and which interact in well-defined ways.

Object-Oriented Paradigms 6

Abstraction and Modularization (Cont.)

• Modularizing the Clock Display

One four-digit display?

Or two two-digit displays?

Object-Oriented Paradigms 7

Implementation - NumberDisplay

public class NumberDisplay{

private int limit;private int value;

Constructor andmethods omitted.

}

Object-Oriented Paradigms 8

Implementation - ClockDisplay

public class ClockDisplay{

private NumberDisplay hours;private NumberDisplay minutes;

Constructor andmethods omitted.

}

Object-Oriented Paradigms 9

Object Diagram

• Object diagram shows the objects interactions. Forexample, myDisplay is an object of class ClockDisplay. It has two fields of type NumberDisplay.

Object-Oriented Paradigms 10

Class Diagram

• Class diagram shows the set of classes that a problem involves with.

Object-Oriented Paradigms 11

Primitive Types and Composite Types

• Data types could be:• Atomic (simple) or primitive type: A data type whose

elements are single, nondecomposable data items; e.g. integer, float, char type.

• Composite type: A data type whose elements are composed of multiple data items; e.g. classes

• Structured composite type: An organized collection of components in which the organization determines the means of accessing individual data components or subsets of the collection; e.g. arrays

Object-Oriented Paradigms 12

Primitive and Composite Data Types (Cont.)

Object-Oriented Paradigms 13

Example: Java’s Built-In Types

Object-Oriented Paradigms 14

Primitive Types vs. Object Types

SomeObject obj;object type

int i;32 primitive type

Object-Oriented Paradigms 15

Primitive Types vs. Object Types

b = a;int a;

32

int b;32

• Assignments on primitive types is different than that on object types. For example:

SomeObject a; SomeObject b;

Object-Oriented Paradigms 16

Source Code: Methods of NumberDisplay

public NumberDisplay(int rollOverLimit){

limit = rollOverLimit;value = 0;

}

public void increment(){

value = (value + 1) % limit;}

Object-Oriented Paradigms 17

Source Code: Methods of NumberDisplay

public String getDisplayValue(){

if(value < 10)return "0" + value;

elsereturn "" + value;

}

Object-Oriented Paradigms 18

Objects Creating Objects

public class ClockDisplay{

private NumberDisplay hours;private NumberDisplay minutes;private String displayString;

public ClockDisplay(){

hours = new NumberDisplay(24);minutes = new NumberDisplay(60);updateDisplay();

}}

Object-Oriented Paradigms 19

Objects Creating Objects (Cont.)

in class NumberDisplay:

public NumberDisplay(int rollOverLimit);

formal parameter

in class ClockDisplay:hours = new NumberDisplay(24);

actual parameter

Object-Oriented Paradigms 20

ClockDisplay Object Diagram

Object-Oriented Paradigms 21

Method Calling

public void timeTick( ){

minutes.increment( );if (minutes.getValue( ) == 0) {

// it just rolled over!hours.increment( );

}updateDisplay( );

}

Object-Oriented Paradigms 22

Internal Method

/*** Update the internal string that represents the* display.*/

private void updateDisplay( ){

displayString = hours.getDisplayValue( ) + ":" + minutes.getDisplayValue( );

}

Object-Oriented Paradigms 23

Method Calls

• internal method calls: use the name of the method;

updateDisplay();…

private void updateDisplay()

• external method calls: use the dot notation

minutes.increment();

Object-Oriented Paradigms 24

Concepts

• abstraction• modularization• classes define types• class diagram• object diagram• object references

• primitive types• object types• object creation• overloading• internal/external

method call

Object-Oriented Paradigms1

Chapter 4Grouping Objects

Collections and Iterators

Topics to be covered:• Collections• Loops• Iterators• Arrays

Object-Oriented Paradigms2

The Requirement to Group Objects

• Many applications involve collections of objects:– Personal organizers.– Library catalogs.– Student-record system.

• The number of items to be stored varies.– Items added.– Items deleted.

Object-Oriented Paradigms3

A Personal Notebook

• Notes may be stored.• Individual notes can be viewed.• There is no limit to the number of notes.• It will tell how many notes are stored.• Explore the notebook1 project.

Object-Oriented Paradigms4

Class Libraries

• Collections of useful classes.• We don’t have to write everything from scratch.• Java calls its libraries, packages.• Grouping objects is a recurring requirement.

- The java.util package contains classesfor doing this.

• Java has a class library called ArrayList in java.util package

• An example (next slide)

Object-Oriented Paradigms5

import java.util.ArrayList;/*** ...*/public class Notebook{

// Storage for an arbitrary number of notes.private ArrayList notes;

/*** Perform any initialization required for the* notebook.*/// Notebook constructorpublic Notebook(){

notes = new ArrayList();}

...}

Object-Oriented Paradigms6

Class Library (Cont.)

• The import statementimport java.util.ArrayList;

illustrates the way in which we gain access to a library class in Java.

• Import statement must always be placed before class definition in a file.

• Using ArrayList object in our class by declaring it:private ArrayList notes;

• Creating an ArrayList object:notes = new ArrayList ( );

Object-Oriented Paradigms7

ArrayList Methods

ArrayList class has the following methods:• add to store an element in the list

public void add (String s)• remove to remove an element from the list

public void remove (String s)• get to get an element from the list

public String get (int n)• size to return the size of the list (number of

elements)public int size ( )

Object-Oriented Paradigms8

Object Structures with Collections

Object-Oriented Paradigms9

Adding a Third Note

Object-Oriented Paradigms10

Features of the collection

• It increases its capacity as necessary.• It keeps a private count (size( ) accessor).• It keeps the objects in order.• Details of how all this is done are hidden.

– Does that matter? Does not knowing how prevent us from using it?

Object-Oriented Paradigms11

Using the Collection

public class Notebook{

private ArrayList notes;...

public void storeNote(String note){

notes.add(note);}

public int numberOfNotes(){

return notes.size();}

...}

Adding a new note

Returning the number of notes(delegation).

Object-Oriented Paradigms12

Index numbering

Object-Oriented Paradigms13

Retrieving an Object

Index validity checks

Retrieve and print the note

public void showNote(int noteNumber){

if(noteNumber < 0) {// This is not a valid note number.

}else if(noteNumber < numberOfNotes()) {

System.out.println(notes.get(noteNumber));}else {

// This is not a valid note number.}

}

Object-Oriented Paradigms14

Removal May Affect Numbering

Object-Oriented Paradigms15

Review• Collections allow an arbitrary number of objects to be

stored.• Class libraries usually contain tried-and-tested collection

classes.• Java’s class libraries are called packages.• We have used the ArrayList class from the java.util

package.• Items may be added and removed.• Each item has an index.• Index values may change if items are removed (or

further items added).• The main ArrayList methods are add, get, remove and

size.

Object-Oriented Paradigms16

Iteration

• We often want to perform some actions an arbitrary number of times.– E.g., print all the notes in the notebook. How

many are there?• Most programming languages include loop

statements to make this possible.• Java has three sorts of loop statement.

– We will focus on its while loop.

Object-Oriented Paradigms17

While Loop Pseudo Code

while(loop condition) {loop body

}

while(there is at least one more note to be printed) {show the next note

}

Boolean testwhile keyword

Statements to be repeated

Pseudo-code example to print every note

General form of a while loop

Object-Oriented Paradigms18

A Java Example

/*** List all notes in the notebook.*/public void listNotes(){

int index = 0;while(index < notes.size( )) {

System.out.println(notes.get(index));index++;

}}

Increment by one

Object-Oriented Paradigms19

Iterating Over a Collection

• To examine every element in the collection, we need an Iterator object.

• ArrayList class provides a special way to iterate over its contents.

• The iterator method of ArrayList returns an Iterator object.

• Iterator is also defined in the java.util package, so we must add a second import statement to the class file:

import java.util.Iterator;

Object-Oriented Paradigms20

Iterating Over a Collection (Cont.)

• Iterator class provides two methods to iterate over collection:- hasNext to check if there are any more

objects in the list- next to get the next object from the list

Object-Oriented Paradigms21

Iterating Over a Collection (Cont.)

java.util.Iterator

Iterator it = myCollection.iterator();while(it.hasNext()) {

call it.next() to get the next objectdo something with that object

}

Returns an Iteratorobject

public void listNotes(){

Iterator it = notes.iterator();while(it.hasNext()) {

System.out.println(it.next());}

}

Object-Oriented Paradigms22

Iterating Over a Collection (Cont.)

• In the last code fragment, we first use the iteratormethod of the ArrayList class to obtain an iteratorobject:

Iterator it = myCollection.iterator ( );• We use that iterator (i.e. it) to repeatedly check

whether there are anymore objects while (it.hasNext ( ))

and to get the next object it.next ( )

• Note that, it is the iterator that we ask to return the next item, and not the collection.

Object-Oriented Paradigms23

Index Access versus Iterators

• We have seen two different ways to iterate over an ArrayList:– By using the get method of ArrayList with an index– By using an Iterator object

• For an ArrayList object, these two ways are good• But Java provides some other collection classes (to be

discussed later). For those collections, it is either impossible or inefficient to access individual elements by providing an index.

• So the second way, using an Iterator, is available for all collections in the Java class library.

Object-Oriented Paradigms24

The Auction Project• The auction project provides further illustration of collections

and iteration.• Two further points to follow up:

– The null value: it means “no object” (when an object variable is not currently referring to a particular object.

– Casting is commonly seen when retrieving objects from the collection. It is required because it is possible to store any type of object in a collection. Casting is needed when using the next method of an iterator, and when using the get method of collection.

e.g. casting is used to store the result of get into a variable:String message = (String) notes.get(0);Lot lot1 = (Lot) it.next ( );

Object-Oriented Paradigms25

Review

• Loop statements allow a block of statements to be repeated.

• A Java while loop allows the repetition to be controlled by a Boolean expression.

• Collection classes have special Iterator objects that simplify iteration over the whole collection.

Object-Oriented Paradigms26

Fixed-Size Collections

• Sometimes the maximum collection size can be pre-determined.

• Programming languages usually offer a special fixed-size collection type: an array.

• Java arrays can store objects or primitive-typevalues.

• Arrays use a special syntax.

Object-Oriented Paradigms27

Projectanalyzer-weblogThe

• Web server records details of each access.• Supports webmaster’s tasks.

– Most popular pages.– Busiest periods.– How much data is being delivered.– Broken references.

• Analyze accesses by hour.

Object-Oriented Paradigms28

Declaring and Creating an Array Object

public class LogAnalyzer{private int[] hourCounts;private LogfileReader reader;

public LogAnalyzer(){

hourCounts = new int[24];reader = new LogfileReader();

}...

}

Array variable declaration

Array object creation

Object-Oriented Paradigms29

The hourCounts Array

Object-Oriented Paradigms30

Using an Array Object• Square-bracket notation is used to access an array element:

hourCounts[...]• An index is used to access any array element.• Using indices outside the bounds of an array will lead to

runtime error called an ArrayOutOfBoundsException.

• Elements are used like ordinary variables.– On the left of an assignment:

hourCounts[hour] = 8 ;– In an expression:

adjusted = hourCounts[hour] – 3;hourCounts[hour]++;

Object-Oriented Paradigms31

The for Loop

• Similar to a while loop.• Often used to iterate a fixed number of times.• Often used to iterate over an array.

Object-Oriented Paradigms32

For Loop Pseudo-Code

General form of a for loop

for(initialization; condition; post-body action) {statements to be repeated

}

Equivalent in while-loop form

initialization;while(condition) {

statements to be repeatedpost-body action

}

Object-Oriented Paradigms33

A Java Example

for loop version

for(int hour = 0; hour < hourCounts.length; hour++) {System.out.println(hour + ": " + hourCounts[hour]);

}

while loop version

int hour = 0;while(hour < hourCounts.length) {

System.out.println(hour + ": " + hourCounts[hour]);hour++;

}

Object-Oriented Paradigms34

Review

• Arrays are appropriate where a fixed-size collection is required.

• Arrays use special syntax.• For loops offer an alternative to while loops

when the number of repetitions is known.• For loops are often used to iterate over arrays.

Object-Oriented Paradigms 1

Chapter 5More Sophisticated Behavior

Main concepts to be covered• Using library classes to implement some

more advanced functionality• Reading documentation• Writing documentation

1.0

Object-Oriented Paradigms 2

The Java Class Library

• Thousands of classes• Tens of thousands of methods• Many useful classes that make life much easier• A competent Java programmer must be able to work

with the libraries.

Object-Oriented Paradigms 3

ibraryLWorking with the

You should:• know some important classes by name;• know how to find out about other classes.

Remember:• We only need to know the interface, not the

implementation.

Object-Oriented Paradigms 4

A Technical Support System: An Example

• As example, Use the TechSupport system which is atextual dialog system

• Its idea is based on ‘Eliza’ (the ground-breaking artificial intelligence program) developed by Joseph Weizenbaum (MIT, 1960s)

• It provides technical support for customers of the fictitious DodgySoft software company.

• Customers can communicate with the technical support system online.

Object-Oriented Paradigms 5

A Technical Support System: An Example

• The project has three classes:- SupportSystem (the main class)- InputReader- Responder

• SupportSystem uses- InputReader to get some input from the terminal- Responder to generate a response

Object-Oriented Paradigms 6

Main Loop Structure in Class SupportSystem

boolean finished = false;

while(!finished) {

do something

if(exit condition) {finished = true;

}else {

do something more}

}

Object-Oriented Paradigms 7

Main Loop Body in Class SupportSystem

String input = reader.getInput();...String response = responder.generateResponse();System.out.println (response);

• The loop repeatedly - reads some user input- asks the responder to generate a response- prints out that response

Object-Oriented Paradigms 8

The Exit Condition in Class SupportSystem

String input = reader.getInput();

if (input.startsWith ("bye")) {finished = true;

}

• Where does ‘startsWith’ come from? (from classString)

• What is it? What does it do?• How can we find out?

Object-Oriented Paradigms 9

Reading Class Documentation

• Documentation of the Java libraries in HTML format;• Readable in a web browser• Class API: Application Programmers’ Interface• Interface description for all library classes

Object-Oriented Paradigms 10

Interface Versus Implementation

The documentation includes• the name of the class;• a general description of the class;• a list of constructors and methods• return values and parameters for

constructors and methods• a description of the purpose of each

constructor and method

the interface of the class

Object-Oriented Paradigms 11

Interface Versus Implementation (Cont.)

The documentation does not include

• private fields (most fields are private)• private methods• the bodies (source code) for each method

the implementation of the class

Object-Oriented Paradigms 12

Using Library Classes

• Classes from the library must be imported using an import statement (except classes from java.lang).

• They can then be used like classes from the current project.

Object-Oriented Paradigms 13

Packages and Import

• Classes are organised in packages.• Single classes may be imported:

import java.util.ArrayList;

• Whole packages can be imported:

import java.util.*;

Object-Oriented Paradigms 14

Side Note: String Equality

if(input == "bye") { tests identity...

}if(input.equals("bye")) { tests equality

...}

• Strings should (almost) always be compared with.equals

Object-Oriented Paradigms 15

Identity Versus Equality 1

Other (non-String) objects:

person1 == person2 ?

“Fred”

:Person

person1 person2

“Jill”

:Person

Object-Oriented Paradigms 16

Identity Versus Equality 2

Other (non-String) objects:

person1 == person2 ?

“Fred”

:Person

person1 person2

“Fred”

:Person

Object-Oriented Paradigms 17

Identity Versus Equality 3

Other (non-String) objects:

person1 == person2 ?

“Fred”

:Person

person1 person2

“Fred”

:Person

Object-Oriented Paradigms 18

Identity Versus Equality (Strings)

"bye"

:String

input

"bye"

:String

String input = reader.getInput();if(input == "bye") {

...}

== tests identity

== ?

(may be) false!

Object-Oriented Paradigms 19

Identity vs Eequality (Strings)

"bye"

:String

input

"bye"

:String

String input = reader.getInput();if(input.equals("bye")) {

...}

equals tests equality

equals ?

true!

Object-Oriented Paradigms 20

Using Random

• The library class Random can be used to generate random numbers

import java.util.Random;...Random randomGenerator = new Random();...int index1 = randomGenerator.nextInt();int index2 = randomGenerator.nextInt(100);

Object-Oriented Paradigms 21

Generating Random Responses

public Responder(){

randomGenerator = new Random();responses = new ArrayList();fillResponses();

}

public String generateResponse(){

int index = randomGenerator.nextInt(responses.size());return (String) responses.get(index);

}

public void fillResponses()...

Object-Oriented Paradigms 22

Maps

• Maps are collections that contain pairs of values.• Pairs consist of a key and a value.• Lookup works by supplying a key, and retrieving a

value.• An example: a telephone book.

Object-Oriented Paradigms 23

Using Maps

• A map with Strings as keys and values

"Charles Nguyen"

:HashMap

"(531) 9392 4587"

"Lisa Jones" "(402) 4536 4674"

"William H. Smith" "(998) 5488 0123"

Object-Oriented Paradigms 24

Using Maps

HashMap phoneBook = new HashMap();

phoneBook.put("Charles Nguyen", "(531) 9392 4587");phoneBook.put("Lisa Jones", "(402) 4536 4674");phoneBook.put("William H. Smith", "(998) 5488

0123");

String number = (String)phoneBook.get("Lisa Jones");System.out.println(number);

Object-Oriented Paradigms 25

Using Setsimport java.util.HashSet;import java.util.Iterator;...HashSet mySet = new HashSet();

mySet.add("one");mySet.add("two");mySet.add("three");

Iterator it = mySet.iterator();while(it.hasNext()) {

call it.next() to get the next objectdo something with that object

}

Compare this to ArrayListcode!

Object-Oriented Paradigms 26

Tokenizing Stringspublic HashSet getInput() {

System.out.print("> "); String inputLine =

readInputLine().trim().toLowerCase();

StringTokenizer tokenizer = new StringTokenizer(inputLine);

HashSet words = new HashSet();

while(tokenizer.hasMoreTokens()) {words.add(tokenizer.nextToken());

}return words;

}

Object-Oriented Paradigms 27

Writing Class Documentation

• Your own classes should be documented the same way library classes are.

• Other people should be able to use your class without reading the implementation.

• Make your class a 'library class'!

Object-Oriented Paradigms 28

Elements of Documentation

Documentation for a class should include:• the class name• a comment describing the overall purpose and

characteristics of the class• a version number• the authors’ names• documentation for each constructor and each method

Object-Oriented Paradigms 29

Elements of Documentation

The documentation for each constructor and method should include:

• the name of the method• the return type• the parameter names and types• a description of the purpose and function of the

method• a description of each parameter• a description of the value returned

Object-Oriented Paradigms 30

javadocClass comment:

/*** The Responder class represents a response* generator object. It is used to generate an * automatic response.* * @author Michael Kölling and David J. Barnes* @version 1.0 (1.Feb.2002)*/

Object-Oriented Paradigms 31

javadoc

Method comment:/*** Read a line of text from standard input (the text terminal), and* return it as a set of words.** @param prompt A prompt to print to screen.* @return A set of Strings, where each String is* one of the words typed by the user*/

public HashSet getInput(String prompt) {

...}

Object-Oriented Paradigms 32

Public Versus Private

• Public attributes (fields, constructors, methods) are accessible to other classes.

• Fields should not be public.• Private attributes are accessible only within the same

class.• Only methods that are intended for other classes

should be public.

Object-Oriented Paradigms 33

Information Hiding

• Data belonging to one object is hidden from other objects.

• Know what an object can do, not how it does it.• Information hiding increases the level of

independence.• Independence of modules is important for large

systems and maintenance.

Object-Oriented Paradigms 34

Class Variables

Object-Oriented Paradigms 35

Constants

private static final int gravity = 3;

• private: access modifier, as usual• static: class variable• final: constant

Object-Oriented Paradigms 36

Review

• Java has an extensive class library.• A good programmer must be familiar with the library.• The documentation tells us what we need to know to

use a class (interface).• The implementation is hidden (information hiding).• We document our classes so that the interface can be

read on its own (class comment, method comments).

Object-Oriented Paradigms 1

Improving Structure With Inheritance

• Main Concept to cover:

• Inheritance• Subtyping• Substitution• Polymorphic variables

Object-Oriented Paradigms 2

The DoME Example

"Database of Multimedia Entertainment"

• stores details about CDs and videos– CD: title, artist, # tracks, playing time, got-it,

comment– Video: title, director, playing time, got-it,

comment• allows (later) to search for information or print

lists

Object-Oriented Paradigms 3

ObjectsDoME

Object-Oriented Paradigms 4

ClassesDoME

Object-Oriented Paradigms 5

DoME Object Model

Object-Oriented Paradigms 6

Class Diagram

Object-Oriented Paradigms 7

CD source code

public class CD {private String title;private String artist;private String comment;

CD(String theTitle, String theArtist){

title = theTitle;artist = theArtist;comment = " ";

}

void setComment(String newComment){ ... }

String getComment(){ ... }

void print(){ ... }...

}

incomplete(comments!)[ ]

Object-Oriented Paradigms 8

Video source code

public class Video {private String title;private String director;private String comment;

Video(String theTitle, String theDirect){

title = theTitle;director = theDirect;comment = " ";

}

void setComment(String newComment){ ... }

String getComment(){ ... }

void print(){ ... }...

}

incomplete(comments!)[ ]

Object-Oriented Paradigms 9

class Database {

private ArrayList cds;private ArrayList videos;...

public void list(){

for(Iterator iter = cds.iterator(); iter.hasNext(); ) {CD cd = (CD)iter.next();cd.print();System.out.println(); // empty line between items

}

for(Iterator iter = videos.iterator(); iter.hasNext(); ) {Video video = (Video)iter.next();video.print();System.out.println(); // empty line between items

}}

}

Database Source Code

Object-Oriented Paradigms 10

DoMECritique of

• code duplication– CD and Video classes very similar (large parts are

identical)– makes maintenance difficult / more work– introduces danger of bugs through incorrect

maintenance• code duplication also in Database class

Object-Oriented Paradigms 11

Using Inheritance

Object-Oriented Paradigms 12

Using Inheritance

• define one superclass : Item

• define subclasses for Video and CD

• the superclass defines common attributes

• the subclasses inherit the superclass attributes

• the subclasses add own attributes

Object-Oriented Paradigms 13

Inheritance Hierarchies

Object-Oriented Paradigms 14

Inheritance in Java

public class Item{

...}

public class CD extends Item{

...}

public class Video extends Item {

...}

no change here

change here

Object-Oriented Paradigms 15

Superclass

public class Item{

private String title;private int playingTime;private boolean gotIt;private String comment;

// constructors and methods omitted.}

Object-Oriented Paradigms 16

Subclasses

public class CD extends Item{

private String artist;private int numberOfTracks;

// constructors and methods omitted.}

public class Video extends Item {

private String director;

// constructors and methods omitted.}

Object-Oriented Paradigms 17

public class Item{

private String title;private int playingTime;private boolean gotIt;private String comment;

/*** Initialise the fields of the item.*/public Item(String theTitle, int time){

title = theTitle;playingTime = time;gotIt = false;comment = "";

}

// methods omitted}

Inheritance and Constructors

Object-Oriented Paradigms 18

Inheritance and Constructors (Cont.)public class CD extends Item{

private String artist;private int numberOfTracks;

/*** Constructor for objects of class CD*/public CD(String theTitle, String theArtist,

int tracks, int time){ //call superclass constructor

super(theTitle, time);artist = theArtist;numberOfTracks = tracks;

}// methods omitted

}

Object-Oriented Paradigms 19

Superclass Constructor Call

• Subclass constructors must always contain a 'super' call.

• If none is written, the compiler inserts one (without parameters)– works only, if the superclass has a constructor

without parameters• Must be the first statement in the subclass

constructor.

Object-Oriented Paradigms 20

Adding More Item Types

Object-Oriented Paradigms 21

Deeper Hierarchies

Object-Oriented Paradigms 22

Review (so far)

Inheritance (so far) helps with:• Avoiding code duplication• Code reuse• Easier maintenance• Extendibility

Object-Oriented Paradigms 23

public class Database{ private ArrayList items;

/*** Construct an empty Database.*/public Database(){

items = new ArrayList();}/*** Add an item to the database.*/public void addItem(Item theItem){

items.add(theItem);}...

}

New Database Source Code

avoids code duplication in client!

Object-Oriented Paradigms 24

/*** Print a list of all currently stored CDs and* videos to the text terminal.*/public void list(){

for(Iterator iter = items.iterator(); iter.hasNext(); ){

Item item = (Item)iter.next();item.print();System.out.println(); // empty line between items

}}

New Database Source Code (Cont.)

Object-Oriented Paradigms 25

Subtyping

First, we had:public void addCD(CD theCD)public void addVideo(Video theVideo)

Now, we have:public void addItem(Item theItem)

We call this method with:Video myVideo = new Video(...);database.addItem(myVideo);

Object-Oriented Paradigms 26

Subclasses and Subtyping

• Classes define types.• Subclasses define subtypes.• Objects of subclasses can be used where

objects of supertypes are required.(This is called substitution .)

Object-Oriented Paradigms 27

Subtyping and Assignment

Vehicle v1 = new Vehicle();Vehicle v2 = new Car();Vehicle v3 = new Bicycle();

subclass objects may be assigned to superclass variables

Object-Oriented Paradigms 28

Subtyping and Parameter Passing

public class Database{

public void addItem(Item theItem){

...}

}

Video video = new Video(...);CD cd = new CD(...);

database.addItem(video);database.addItem(cd);

subclass objects may be passed to superclass parameters

Object-Oriented Paradigms 29

Object iagram

Object-Oriented Paradigms 30

Object Diagram

Object-Oriented Paradigms 31

Class Diagram

Object-Oriented Paradigms 32

Polymorphic Variables

• Object variables in Java are polymorphic.

(That is, They can hold objects of more than one type)

• They can hold objects of the declared type, or of subtypes of the declared type.

Object-Oriented Paradigms 33

The Object Class

All classes inherit from Object.

Object-Oriented Paradigms 34

Polymorphic Collections

• All collections are polymorphic.• The elements are of type Object.

public void add(Object element)

public Object get(int index)

Object-Oriented Paradigms 35

Casting Revisited

• Can assign subtype to supertype.• Cannot assign supertype to subtype!

String s1 = myList.get(1); error!

• Casting fixes this:String s1 = (String) myList.get(1);

(only if the element really is a String!)

Object-Oriented Paradigms 36

Wrapper Classes

• All objects can be entered into collections...• ...because collections accept elements of type

Object...• ...and all classes are subtypes of Object.• Great! But what about simple types?

Object-Oriented Paradigms 37

Wrapper Classes (Cont.)

• Simple types (int, char, etc) are not objects. They must be wrapped into an object!

• Wrapper classes exist for all simple types:

simple type wrapper classint Integerfloat Floatchar Character... ...

Object-Oriented Paradigms 38

Wrapper Classes (Cont.)

int i = 18; Integer iwrap = new Integer(i);

myCollecton.add(iwrap);...

Integer element = (Integer) myCollection.get(0);int value = element.intValue()

wrap the int value

add the wrapper

retrieve the wrapper

unwrap

Object-Oriented Paradigms 39

Review

• Inheritance allows the definition of classes as extensions of other classes.

• Inheritance – avoids code duplication– allows code reuse– simplifies the code– simplifies maintenance and extending

• Variables can hold subtype objects.• Subtypes can be used wherever supertype objects are

expected (substitution).

Object-Oriented Paradigms 1

Chapter 9: More About InheritanceExploring Polymorphism

Main concepts to be covered• Method Polymorphism• Static and Dynamic Type• Overriding• Dynamic Method Lookup• Protected Access

Object-Oriented Paradigms 2

The Inheritance Hierarchy

Object-Oriented Paradigms 3

Conflicting Output

CD: A Swingin' Affair (64 mins)*Frank Sinatratracks: 16my favourite Sinatra album

video: The Matrix (136 mins)Andy & Larry Wachowskimust see if interested in virtual reality!

title: A Swingin' Affair (64 mins)*my favourite Sinatra album

title: The Matrix (136 mins)must see if interested in virtual reality!

What we want

What we now have

Object-Oriented Paradigms 4

The Problem

• The print method in Item class only prints the common fields.

• Inheritance is a one-way street:– A subclass inherits the superclass fields.– The superclass knows nothing about its

subclass’s fields.

Object-Oriented Paradigms 5

Attempting to Solve The Problem

• Place print where it has access to the information it needs.

• Each subclass has its own version.

• But Item’s fields are private.

• Database cannot find a print method in Item.

Object-Oriented Paradigms 6

Attempting to Solve The Problem

In the previous model there are some errors:1) The subclass cannot access the supper class fields:

Reason: they are declared as privateSolution:

- define public accessor methods for them, since wedo not want to break encapsulation and make thesevariables public

- other solution will be discussed later

(2) Database class cannot find the print methodSolution: see next slides

Object-Oriented Paradigms 7

Static Type and Dynamic Type

• A more complex type hierarchy requires further concepts to describe it.

• Some new terminology:– static type– dynamic type– method dispatch/lookup

Object-Oriented Paradigms 8

Static and Dynamic Type

Car c1 = new Car();What is the type of c1?

Vehicle v1 = new Car();What is the type of v1?

Object-Oriented Paradigms 9

Static and Dynamic Type (Cont.)• The declared type of a variable is its static type, because it is declared in the source code

• The type of the object a variable refers to is its dynamic type, because it depends on assignments at runtime.

• The compiler’s job is to check for static-type violations.Item item = (Item) iter.next();item.print(); // Compile-time error.

(This is because the static type of item is Item, while the dynamic type is either CD or Video. We do not know which one of these it is.)

Object-Oriented Paradigms 10

Overriding: The Solution

print method in both super-and subclasses.

Satisfies both static and

dynamic type checking.

Object-Oriented Paradigms 11

The print Method in Super and Sub Classes

public class Item{ …

public void print ( ){ System.out.println (title+“ (“ + playingTime + “ mins}”);

if (gotIt){System.out.println ( “ * “ ); }

else{System.out.println (“ “ + comment); }

}

Object-Oriented Paradigms 12

The print Method in Super and Sub Classes

public class CD extends Item{ public void print ( )

{ System.out.println (“ “ + artist);System.out.println (“ tracks: “ + numberOf

Tracks);}

}

public class Video extends Item{ public void print ( )

{ System.out.println (“ “ + director); }}

Object-Oriented Paradigms 13

Overriding

• Superclass and subclass define methods with the same signature.

• Each has access to the fields of its class.• Superclass satisfies static type check.• Subclass method is called at runtime – it overrides

the superclass version.• What becomes of the superclass version?

Object-Oriented Paradigms 14

Method Lookup

No inheritance or polymorphism.The obvious method is selected.

Object-Oriented Paradigms 15

Method Lookup (Cont.)

Inheritance but no overriding. The inheritance

hierarchy is ascended, searching for a match.

Object-Oriented Paradigms 16

Method Lookup (Cont.)

Polymorphism and overriding. The ‘first’version found is used.

Object-Oriented Paradigms 17

Method Lookup Summary

• The variable is accessed.• The object stored in the variable is found.• The class of the object is found.• The class is searched for a method match.• If no match is found, the superclass is searched.• This is repeated until a match is found, or the class

hierarchy is exhausted.• Overriding methods take precedence.

Object-Oriented Paradigms 18

Super Call in Methods

• Overridden methods are hidden ...• ... but we often still want to be able to call them.• An overridden method can be called from the

method that overrides it.– super.method(...)– Compare with the use of super in constructors.

Object-Oriented Paradigms 19

Calling an Overridden Method

public class CD{

...public void print(){

super.print();System.out.println(" " + artist);System.out.println("tracks: " +

numberOfTracks);}...

}

Object-Oriented Paradigms 20

Method Polymorphism

• We have been discussing polymorphic methoddispatch.

• A polymorphic variable can store objects of varying types.

• Method calls are polymorphic.– The actual method called depends on the

dynamic object type.

Object-Oriented Paradigms 21

The Object Class’s Methods

• Methods in Object are inherited by all classes.• Any of these may be overridden.

• The toString method of Object is commonly overridden:– public String toString()– Returns a string representation of the object.

Object-Oriented Paradigms 22

Overriding toString Methodpublic class Item{

...public String toString(){ String line1 = title +

" (" + playingTime + " mins)"); if(gotIt) {

return line1 + "*\n" + " " +comment + "\n");

} else {return line1 + "\n" + " " +

comment + "\n");}

}...

}

Object-Oriented Paradigms 23

Overriding toString Method (Cont.)

• Explicit print methods can often be omitted from a class:– System.out.println(item.toString());

• Calls to println with just an object automatically result in toString being called:– System.out.println (item);

Object-Oriented Paradigms 24

Protected Access

• Private access in the superclass may be too restrictive for a subclass.

• The closer inheritance relationship is supported by protected access.

• Protected access is more restricted than public access.

• We still recommend keeping fields private.– Define protected accessors and mutators.

Object-Oriented Paradigms 25

Access Levels

Object-Oriented Paradigms 26

Review

• The declared type of a variable is its static type.– Compilers check static types.

• The type of an object is its dynamic type.– Dynamic types are used at runtime.

• Methods may be overridden in a subclass.• Method lookup starts with the dynamic type.• Protected access supports inheritance.

Object-Oriented Paradigms 1

Chapter 10:Further Abstraction TechniquesAbstract Classes and Interfaces

Main concepts to be covered:• Abstract classes• Interfaces• Multiple inheritance

1.0

Object-Oriented Paradigms 2

Simulations

• Programs regularly used to simulate real-world activities.– city traffic– the weather– nuclear processes– stock market fluctuations– environmental changes

• They are often only partial simulations.• They often involve simplifications.

– Greater detail has the potential to provide greater accuracy.– Greater detail typically requires more resource.

• Processing power.• Simulation time.

Object-Oriented Paradigms 3

Benefits of Simulations

• Support useful prediction.– The weather.

• Allow experimentation.– Safer, cheaper, quicker.

• Example:– ‘How will the wildlife be affected if we cut a

highway through the middle of this national park?’

Object-Oriented Paradigms 4

Predator-Prey Simulations• Such simulations are often used to model the

variation in population sizes that result from a predator species feeding on a prey species.

• There is often a delicate balance between species.– A lot of prey means a lot of food.– A lot of food encourages higher predator numbers.– More predators eat more prey.– Less prey means less food.– Less food means ...

Object-Oriented Paradigms 5

The Foxes-and-Rabbits Project

Object-Oriented Paradigms 6

Main Classes of Interest

• Fox– Simple model of a type of predator.

• Rabbit– Simple model of a type of prey.

• Simulator– Manages the overall simulation task.– Holds a collection of foxes and rabbits.– Performs a sequence of steps.– In each step, each fox and each rabbit is allowed to

move. After each step, the current state if the field is displayed on screen.

Object-Oriented Paradigms 7

The Remaining Classes• Field

– Represents a 2D field. It is composed of a fixed number of locations (arranged in rows and columns)

– At most one animal may occupy a single location within the field.• Location

– Represents a 2D position within the field. Its position is determined by a row and a column value.

• SimulatorView, FieldStats, Counter- Maintain statistics and present a view of the field.

• SimulatorView:- provides a graphical visualization of the state of the field (see next slide).

• FieldStats- provides counts of the numbers of foxes & rabbits in the field to the visualization.

• Counter- stores a current count for one type of animal to assist with the counting.

Object-Oriented Paradigms 8

Example of The Visualization

Object-Oriented Paradigms 9

A Rabbit’s State

public class Rabbit{ Static fields omitted.

// Individual characteristics (instance fields).// The rabbit's age.private int age;// Whether the rabbit is alive or not.private boolean alive;// The rabbit's positionprivate Location location;

Method omitted.}

Object-Oriented Paradigms 10

A Rabbit’s Behavior

• Managed from the run method.• Age incremented at each simulation ‘step’.

– A rabbit could die at this point.• Rabbits that are old enough might breed at each step.

– New rabbits could be born at this point.

Object-Oriented Paradigms 11

Rabbit Simplifications

• Rabbits do not have different genders.– In effect, all are female.

• The same rabbit could breed at every step.• All rabbits die at the same age.• Others?

Object-Oriented Paradigms 12

A Fox’s State

public class Fox{ Static fields omitted

// The fox's age.private int age;// Whether the fox is alive or not.private boolean alive;// The fox's positionprivate Location location;// The fox's food level, which is increased by eating// rabbits.private int foodLevel;

Methods omitted.}

Object-Oriented Paradigms 13

A Fox’s Behavior

• Managed from the hunt method.• Foxes also age and breed.• They become hungry.• They hunt for food in adjacent locations.

Object-Oriented Paradigms 14

Configuration of Foxes

• Similar simplifications to rabbits.• Hunting and eating could be modeled in many

different ways.– Should food level be additive?– Is a hungry fox more or less likely to hunt?

• Are simplifications ever acceptable?

Object-Oriented Paradigms 15

The Simulator Class

• Three key components:– Setup in the constructor.– The populate method.

• Each animal is given a random starting age.– The simulateOneStep method.

• Iterates over the population.• Two Field objects are used: field and updatedField.

Object-Oriented Paradigms 16

The Update Stepif (animal instanceof Rabbit){ Rabbit rabbit = (Rabbit) animal;

if (rabbit.isAlive ( ) ) { rabbit.run (updatedField, newAnimals); }else{ iter.remove ( ); }

}else if (animal instanceof Fox) { Fox fox = (Fox) animal;

if (fox.isAlive ( ) ){ fox.hunt (field, updatedField, newAnimals); }else{ iter.remove ( ); }

}

Object-Oriented Paradigms 17

Room for Improvement

• Fox and Rabbit have strong similarities but do nothave a common superclass.

• The Simulator is tightly coupled to specific classes.– It ‘knows’ a lot about the behavior of foxes and

rabbits.

Object-Oriented Paradigms 18

The Animal Superclass

• Place common fields in Animal:– age, alive, location

• Method renaming to support information hiding:– run and hunt become act.

• Simulator can now be significantly decoupled.

Object-Oriented Paradigms 19

Revised (Decoupled) Iteration

for(Iterator iter = animals.iterator(); iter.hasNext(); )

{ Animal animal = (Animal)iter.next();if(animal.isAlive()) { animal.act(field, updatedField,

newAnimals);}else{ iter.remove(); }

}

Object-Oriented Paradigms 20

The Act Method of Animal• Static type checking requires an act method in Animal.

• There is no obvious shared implementation.• Define act as abstract:

abstract public void act( Field currentField,Field updatedField,List newAnimals);

Object-Oriented Paradigms 21

Abstract Classes and Methods

• Abstract methods have abstract in the signature.• Abstract methods have no body.• Abstract methods make the class abstract.• Abstract classes cannot be instantiated.• Concrete subclasses complete the implementation.

Object-Oriented Paradigms 22

The Animal Class

public abstract class Animal{ fields omitted

/*** Make this animal act - that is: make it do* whatever it wants/needs to do.*/abstract public void act ( Field currentField,

Field updatedField,List newAnimals);

other methods omitted}

Object-Oriented Paradigms 23

Further Abstraction

Object-Oriented Paradigms 24

Selective Drawing(Multiple Inheritance)

Object-Oriented Paradigms 25

Multiple Inheritance

• Having a class inherit directly from multiple ancestors.

• Each language has its own rules.– How to resolve competing definitions?

• Java forbids it for classes.• Java permits it for interfaces.

– No competing implementation.

Object-Oriented Paradigms 26

An Actor Interface

public interface Actor{ /**

* Perform the actor's daily behavior.* Transfer the actor to updatedField if it is to participate in* further steps of the simulation.* @param currentField The current state of the field.* @param location The actor's location in the field.* @param updatedField The updated state of the field.*/void act ( Field currentField, Location location,

Field updatedField);}

Object-Oriented Paradigms 27

Classes Implement an Interface

public class Fox extends Animal implements Drawable{

...}

public class Hunter implements Actor, Drawable{

...}

Object-Oriented Paradigms 28

Interfaces as Types

• Implementing classes do not inherit code, but ...• ... implementing classes are subtypes of the interface

type.• So, polymorphism is available with interfaces as well

as classes.

Object-Oriented Paradigms 29

Interfaces as Specifications

• Strong separation of functionality from implementation.– Though parameter and return types are mandated.

• Clients interact independently of the implementation.– But clients can choose from alternative

implementations.

Object-Oriented Paradigms 30

Alternative Implementations

Object-Oriented Paradigms 31

Review

• Inheritance can provide shared implementation.– Concrete and abstract classes.

• Inheritance provides shared type information.– Classes and interfaces.

• Abstract methods allow static type checking without requiring implementation.

• Abstract classes function as incomplete superclasses.– No instances.

• Abstract classes support polymorphism.

Object-Oriented Paradigms 32

Interfaces

• Interfaces provide specification without implementation.– Interfaces are fully abstract.

• Interfaces support polymorphism.• Java interfaces support multiple inheritance.

Recommended