Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf ·...

260
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-PDF MERGER DEMO

Transcript of Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf ·...

Page 1: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 2: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object Oriented Paradigms by Dr. Nadia Y. Yousif

2

Object-Oriented Programming (721112)

Lecturer: Dr. Nadia Y. Yousif

Email: [email protected]@hotmail.com

Room: IT 332

Page 3: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 4: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 5: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 6: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 7: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 8: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object Oriented Paradigms by Dr. Nadia Y. Yousif

8

Lecturer and Consultation

• Lecturer:Dr. Nadia Y. YousifFaulty of IT, Room 332, Phone Ext: 2544email: [email protected]

• 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

Page 9: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 10: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 11: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 12: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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?

Page 13: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 14: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 15: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 16: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 17: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 18: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 19: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 20: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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)

Page 21: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 22: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 23: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 24: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 25: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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, ...)• ...

Page 26: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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?- …

Page 27: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 28: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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?

Page 29: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 30: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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!

Page 31: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 32: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object Oriented Paradigms by Dr. Nadia Y. Yousif

32

Discovering Classes

• Noun phrase approach• “Object Think”• Hybrids

Page 33: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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 ?

Page 34: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 35: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 36: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 37: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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 ...

Page 38: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 39: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 40: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 41: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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)

Page 42: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 43: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 44: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 45: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 46: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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();

Page 47: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 48: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object Oriented Paradigms by Dr. Nadia Y. Yousif

48

State

Page 49: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object Oriented Paradigms by Dr. Nadia Y. Yousif

49

Two Circle Objects

Page 50: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 51: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 1

Chapter 2Understanding Class Definitions

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

Page 52: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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?

Page 53: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 54: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 55: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 56: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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;

}

Page 57: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 7

Passing Data via Parameters

Page 58: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 59: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 60: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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)

Page 61: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 62: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 63: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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;

}

Page 64: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 65: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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);}

}

Page 66: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 67: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 68: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 18

Local variables

public int refundBalance(){

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

}

A local variable

No visibilitymodifier

Page 69: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 70: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 71: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 2

An Example: A Digital Clock

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

Page 72: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 73: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 4

Abstraction and Modularization (Cont.)

• Example: A car is viewed by two different ways

Page 74: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 75: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 6

Abstraction and Modularization (Cont.)

• Modularizing the Clock Display

One four-digit display?

Or two two-digit displays?

Page 76: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 7

Implementation - NumberDisplay

public class NumberDisplay{

private int limit;private int value;

Constructor andmethods omitted.

}

Page 77: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 8

Implementation - ClockDisplay

public class ClockDisplay{

private NumberDisplay hours;private NumberDisplay minutes;

Constructor andmethods omitted.

}

Page 78: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 79: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 10

Class Diagram

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

Page 80: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 81: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 12

Primitive and Composite Data Types (Cont.)

Page 82: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 13

Example: Java’s Built-In Types

Page 83: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 14

Primitive Types vs. Object Types

SomeObject obj;object type

int i;32 primitive type

Page 84: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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;

Page 85: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 16

Source Code: Methods of NumberDisplay

public NumberDisplay(int rollOverLimit){

limit = rollOverLimit;value = 0;

}

public void increment(){

value = (value + 1) % limit;}

Page 86: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 17

Source Code: Methods of NumberDisplay

public String getDisplayValue(){

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

elsereturn "" + value;

}

Page 87: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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();

}}

Page 88: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 89: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 20

ClockDisplay Object Diagram

Page 90: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 21

Method Calling

public void timeTick( ){

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

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

}updateDisplay( );

}

Page 91: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 22

Internal Method

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

private void updateDisplay( ){

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

}

Page 92: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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();

Page 93: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 94: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms1

Chapter 4Grouping Objects

Collections and Iterators

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

Page 95: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 96: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 97: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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)

Page 98: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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();}

...}

Page 99: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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 ( );

Page 100: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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 ( )

Page 101: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms8

Object Structures with Collections

Page 102: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms9

Adding a Third Note

Page 103: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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?

Page 104: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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).

Page 105: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms12

Index numbering

Page 106: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.}

}

Page 107: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms14

Removal May Affect Numbering

Page 108: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 109: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 110: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 111: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 112: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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;

Page 113: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 114: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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());}

}

Page 115: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 116: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 117: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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 ( );

Page 118: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 119: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 120: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 121: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 122: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms29

The hourCounts Array

Page 123: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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]++;

Page 124: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 125: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

}

Page 126: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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++;

}

Page 127: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 128: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 129: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 130: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 131: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 132: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 133: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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}

}

Page 134: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 135: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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?

Page 136: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 137: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 138: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 139: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 140: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.*;

Page 141: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 142: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 15

Identity Versus Equality 1

Other (non-String) objects:

person1 == person2 ?

“Fred”

:Person

person1 person2

“Jill”

:Person

Page 143: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 16

Identity Versus Equality 2

Other (non-String) objects:

person1 == person2 ?

“Fred”

:Person

person1 person2

“Fred”

:Person

Page 144: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 17

Identity Versus Equality 3

Other (non-String) objects:

person1 == person2 ?

“Fred”

:Person

person1 person2

“Fred”

:Person

Page 145: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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!

Page 146: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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!

Page 147: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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);

Page 148: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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()...

Page 149: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 150: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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"

Page 151: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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);

Page 152: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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!

Page 153: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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;

}

Page 154: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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'!

Page 155: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 156: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 157: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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)*/

Page 158: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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) {

...}

Page 159: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 160: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 161: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 34

Class Variables

Page 162: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 35

Constants

private static final int gravity = 3;

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

Page 163: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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).

Page 164: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 1

Improving Structure With Inheritance

• Main Concept to cover:

• Inheritance• Subtyping• Substitution• Polymorphic variables

Page 165: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 166: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 3

ObjectsDoME

Page 167: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 4

ClassesDoME

Page 168: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 5

DoME Object Model

Page 169: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 6

Class Diagram

Page 170: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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!)[ ]

Page 171: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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!)[ ]

Page 172: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 173: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 174: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 11

Using Inheritance

Page 175: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 176: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 13

Inheritance Hierarchies

Page 177: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 178: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 15

Superclass

public class Item{

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

// constructors and methods omitted.}

Page 179: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.}

Page 180: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 181: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

}

Page 182: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 183: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 20

Adding More Item Types

Page 184: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 21

Deeper Hierarchies

Page 185: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 22

Review (so far)

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

Page 186: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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!

Page 187: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.)

Page 188: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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);

Page 189: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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 .)

Page 190: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 191: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 192: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 29

Object iagram

Page 193: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 30

Object Diagram

Page 194: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 31

Class Diagram

Page 195: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 196: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 33

The Object Class

All classes inherit from Object.

Page 197: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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)

Page 198: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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!)

Page 199: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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?

Page 200: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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... ...

Page 201: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 202: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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).

Page 203: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 204: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 2

The Inheritance Hierarchy

Page 205: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 206: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 207: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 208: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 209: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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

Page 210: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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?

Page 211: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.)

Page 212: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 10

Overriding: The Solution

print method in both super-and subclasses.

Satisfies both static and

dynamic type checking.

Page 213: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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); }

}

Page 214: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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); }}

Page 215: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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?

Page 216: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 14

Method Lookup

No inheritance or polymorphism.The obvious method is selected.

Page 217: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 15

Method Lookup (Cont.)

Inheritance but no overriding. The inheritance

hierarchy is ascended, searching for a match.

Page 218: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 16

Method Lookup (Cont.)

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

Page 219: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 220: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 221: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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);}...

}

Page 222: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 223: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 224: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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");}

}...

}

Page 225: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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);

Page 226: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 227: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 25

Access Levels

Page 228: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 229: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 1

Chapter 10:Further Abstraction TechniquesAbstract Classes and Interfaces

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

1.0

Page 230: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 231: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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?’

Page 232: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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 ...

Page 233: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 5

The Foxes-and-Rabbits Project

Page 234: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 235: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 236: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 8

Example of The Visualization

Page 237: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.}

Page 238: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 239: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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?

Page 240: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.}

Page 241: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 242: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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?

Page 243: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 244: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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 ( ); }

}

Page 245: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 246: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 247: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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(); }

}

Page 248: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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);

Page 249: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 250: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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}

Page 251: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 23

Further Abstraction

Page 252: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 24

Selective Drawing(Multiple Inheritance)

Page 253: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 254: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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);}

Page 255: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 27

Classes Implement an Interface

public class Fox extends Animal implements Drawable{

...}

public class Hunter implements Actor, Drawable{

...}

Page 256: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 257: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 258: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 30

Alternative Implementations

Page 259: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

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.

Page 260: Object-Oriented Programming (721112) - Philadelphia University Files/cs/721112le.pdf · Object-Oriented Programming (721112) A Core Module for Students in CS, CIS, SE, ACS Departments

Object-Oriented Paradigms 32

Interfaces

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

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