1 intro to programming & algorithm design object oriented programming copyright 2003 by janson...

199
1 Programming & Algorithm Design Object Oriented Programmin g right 2003 by Janson Industries This presentation can be viewed on line in a file named: ch10.IntrotoProg.OOP.ppt Assg

Upload: matthew-richard

Post on 13-Jan-2016

227 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

1

Intro to Programming & Algorithm Design

Object

Oriented

Programming

Copyright 2003 by Janson Industries

This presentation can be viewed on line in a file named: ch10.IntrotoProg.OOP.ppt

Assg

Page 2: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries2

Objectives Explain

OOP vs. Procedural Programming

Inheritance and Composition

Encapsulation

Access specifiers/modifiers

Polymorphism

Demonstrate

Good OOP techniques

Page 3: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries3

OOP vs. Procedural Lots of differences

How they are executed/run

How programs and objects are related to other programs and objects

How programs vs. objects interact with data

Objects have greater reusability than procedural programs

Page 4: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries4

OOP vs. Procedural When creating a procedural

program, concentrate on the steps need to complete task

When an object is created, try to have it mirror a real world thing

Example: Scanner Created a Scanner object to

access data from the console and files

Page 5: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries5

OOP vs. Procedural Scanner highlights some other

aspects of OOP

The internal workings of objects are hidden from the user of the object Do you have any idea how

nextLine() works? You know how to use it, but not

how it works

Page 6: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries6

OOP vs. Procedural Isn't that a lot like the real world?

Do you have to know how internal combustion works to drive a car?

Do you have to know what those holes in a cinderblock are for to use one?

All you have to know is the interface to the object Step on right pedal – car go faster

Step on left pedal – car go slower

Page 7: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries7

OOP vs. Procedural Objects also are much more tightly

entwined with the data The user of the object cannot directly access

the data

Has to use object methods to retrieve or set the data values

With Scanner you used next(), nextLine(), nextInt, etc. to access data

This is called data hiding or data encapsulation

Page 8: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries8

OOP Concepts The programmer creates classes

The class contains the programming code that defines all the variables and methods of a particular object

An object is created from the class

Page 9: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries9

OOP Concepts A class is like a blue print

Many houses (objects) created from a blueprint (class)

Each house (object) is unique though

Painted a different color Different counter tops Different flooring

All the houses have common characteristics but are unique

Page 10: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries10

OOP Concepts Like a dog

All dogs have common characteristics

Name, Type of dog, Hair color, Height, Weight

But each dog is unique Buster the pit bull is very different

from Fifi the poodle Even Billy the basset is different

from Barney the basset

Page 11: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries11

OOP Example We'll create a class called Employee

It will have 4 attributes (characteristics) Employee name Pay rate Hours worked Pay

Then show how a Payroll app would use the Employee class to create and use Employee objects

Page 12: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries12

OOP Example Classes start with "Class" and the

class name

Classes end with "End Class"

Also, when an object is created from the class, the classes constructor method is run A constructor has the same name as the

class and returns nothing

Class Employee executable statementsEnd Class

Page 13: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries13

OOP Example Assumes we have

A payroll file with all employee data

An employee file (named EmployeeList.data ) with all the employee names

We'll define 4 variables to hold the Employee object's unique info

And create a method to calc pay

Page 14: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries14

Object Oriented Employee ClassClass Employee

Declare String empName Declare real payrate, hours, pay Declare InputFile payrollFile

Open payrollFile "Payroll.dat" Module Employee(String name)

Read payrollFile payrate, hours, empName While empName <> name

Read payrollFile payrate, hours, empName

End While Close payrollFile

End ModuleFunction real getPay()

pay = payrate * hoursReturn pay

End FunctionEnd Class

GlobalVariables

Open file

Search for employee info

Page 15: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries15

Object Oriented Employee Class

Module Employee(String name)Read payrollFile payrate, hours, empName While empName <> name

Read payrollFile payrate, hours, empName

End While Close payrollFile

End Module

This is the constructor

It will be run when the object is created Notice that it expects a name and

uses name to search the file

Page 16: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries16

Object Oriented Employee Class

Module Employee(String name)Read payrollFile payrate, hours, empName While empName <> name

Read payrollFile payrate, hours, empName

End While Close payrollFile

End Module

Notice that the constructor "initializes" the object

I.e. it gets all the employee data that makes this employee object unique and useful

Page 17: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries17

Object Oriented Employee Class This means that the program

creating the Employee object must supply a name

The way to create a object is to use the keyword New then the class name and any parameters

If you want to access the object, must assign it to a variable

New Employee("John Smith")

Page 18: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries 18

Object Oriented Employee Class Can do it like this

Or in one statement like this:

To invoke an object's methods, specify the variable name, a period, then the method name

Just like keyboard.nextLine()

Employee empObjectempObject = New Employee("John Smith")

Employee empObject = New Employee("John Smith")

pay = empObject.getPay()

Page 19: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries19

Object Oriented Payroll PgmModule main()

Declare String empNameDeclare InputFile employeeFile

Open employeeFile "EmployeeList.dat"Declare Employee empWhile NOT eof(employeeFile)

Read employeeFile empNameemp = New Employee(empName)

Print empName, emp.getPay()End While

Close employeeFile End Module

String variable

Opens file

Reads file

Creates Employee

object InvokesgetPay

Employee variable

Page 20: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries20

Object Oriented Payroll Pgm Notice the payroll pgm

Has no idea how pay is calculated Hourly? Salary?

Has no access to payrate or hours

Can only access pay through the object's getPay method

Created many unique Employee objects from the one Employee class

Page 21: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries21

Procedural Payroll PgmModule main()

Declare String empName Declare real payrate, hours, pay Declare InputFile payrollFile

Open payrollFile "Payroll.dat" While NOT eof(payrollFile)

Read payrollFile payrate, hours, empName

pay = payrate * hoursPrint empName, pay

End While Close payrollFileEnd Module

Page 22: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries22

OOP vs. Procedural What happens with the

procedural app if we want to create a new app that allows a user to enter a name and the pay is shown?

Have to create new program and duplicate all the payroll logic

Page 23: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries23

Procedural Display Pay PgmModule main()

Declare String empName, name Declare real payrate, hours, pay Declare InputFile payrollFile

Open payrollFile "Payroll.dat" Display "What is the employee's name" Input name Read payrollFile payrate, hours, empName

While empName <> nameRead payrollFile payrate, hours,

empName End While

Close payrollFile pay = payrate * hours Display empName, pay

End Module

Page 24: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries24

OO Display Pay Pgm

Module main() Declare String name Declare real pay Declare Employee emp Display "What is the employee's name?" Input name emp = New Employee(name) pay = emp.getPay() Display name, pay

End Module

Page 25: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries25

OOP vs. Procedural Notice the pay calculation logic not

duplicated

Were able to reuse the logic in the Employee class

Notice how much simpler the program is

And if the payroll calculation logic ever changes (go from hourly to salary) only change in one place – the Employee class

Page 26: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries26

Variables Can define class/global variables

Can be accessed by all methods in the class

Defined after class header and before any modules/methods

Local variables defined in a method Can only be accessed by the method that

defines it

Page 27: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries27

Access Modifiers/Specifiers Can define whether other classes can

use/access methods and variables Private means only the class that defines

the method/module and access/use it

Public means any class can access/use it

To protect data, most variables defined as Private This is how we "hide" data

Page 28: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries28

Access Modifiers/Specifiers However all those methods that provide access

to the Private data are defined as Public These methods are generally called getters and

setters (fancy names - accessors and mutators) There's one getter and one setter for each Private

variable

The setter and getter method names begin with the word set and get and then the variable name

So for Employee we should have…

Page 29: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries29

Object Oriented Employee ClassClass Employee

Declare Private String empName Declare Private real payrate, hours, pay Declare InputFile payrollFile

Open payrollFile "Payroll.dat"

Public Module Employee(String name)Read payrollFile payrate, hours, empName While empName <> name Read payrollFile payrate, hours,

empNameEnd While

Close payrollFileEnd Module

Public Function real getPay()pay = payrate * hoursReturn pay

End Function

Page 30: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries30

Object Oriented Employee Class Public Function real getPayrate()

Return payrate End Function Public Function real getHours()

Return hours End Function Public Function String getEmpName()

Return empName End Function Public Module setPayrate(real pr)

payrate = pr End Module Public Module setHours(real hrs)

hours = hrs End Module Public Module setEmpName(String eName)

empName = eName End Module

End Class

getters

setters

Page 31: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries31

Getters and Setters Notice in the pseudocode that the

getters are defined as functions and setters are modules

Page 32: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries32

Object Exercise Assg 1 Create pseudocode for a class called Auto that

Has 3 global Private String variables called make model vin

A constructor that does nothing

Solution

Page 33: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries33

OOP vs. Procedural A class can be run as a

procedural pgm That’s what we have been doing for

the last 13 weeks

Main method loaded into MM and executed

If main calls a static method that method is loaded into MM and executed

Page 34: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries34

Objects With OOP, creating an object means

an "instance of a class" is created "Class instance" is an "object"

When an object is created All of the class's methods and variables

are loaded into MM The constructor is executed

Constructor is a method With the same name as the class Doesn't return any value

Page 35: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries35

Example Two classes

ClassRunAsApp ClassInstantiatedAsObject

Identical (except for name) have main methods constructors

mains and constructors Both print out the class name appended with text

main prints "main method" Constructor prints "constructor"

Page 36: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries36

Example Pseudocode

Class ClassRunAsApp Declare Private String constructorName = “ClassRunAsApp's constructor”

Public Module ClassRunAsApp()Display constructorName

End Module

Module main() Declare String mainName =

"ClassRunAsApp's main method”Display mainName

End Module

End Class

Two String variables

Main displays one, constructor the other

constructor

main

Page 37: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries37

Example Pseudocode

Class ClassInstantiatedAsObject

Declare Private String constructorName = “ClassInstantiatedAsObject's constructor”

Public Module ClassInstantiatedAsObject() Display constructorName End Module

Module main() Declare String mainName =

"ClassInstantiatedAsObject's main method” Display mainName End Module

End Class

Page 38: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

Now we need a class to create a ClassInstantiatedAsObject object ObjectExample

Most of the time the object will be assigned to a variable

38

Object Example

Class ObjectExample

Module main()New ClassInstantiatedAsObject()

End Module

End Class

Declare ClassInstantiatedAsObject cias = New ClassInstantiatedAsObject()

Page 39: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries39

Object Exercise Assg 2 Create pseudocode for a class

called AutoCreate that

Creates 2 Auto objects

Assigns them to Private global variables called

carOnecarTwo

Solution

Page 40: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries40

Example Java

public class ClassRunAsApp {String constructorName = "ClassRunAsApp's

constructor";

public ClassRunAsApp() {System.out.println(constructorName);

}

public static void main(String[] args) {String mainName = "ClassRunAsApp's main

method";System.out.println(mainName);

}}

Page 41: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries41

Example Java

public class ClassInstantiatedAsObject { String constructorName = "ClassInstantiatedAsObject's constructor"; public ClassInstantiatedAsObject() {

System.out.println(constructorName); }

public static void main(String[] args) {String mainName = "ClassInstantiatedAsObject's main

method";System.out.println(mainName);

}}

Page 42: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries42

Nothing new here. When a ClassRunAsApp is run as a java app , the main method (not the constructor) is executed

Page 43: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

Will create a ClassInstantiatedAsObject object

Here's the Java version

When ObjectExample is run...43

Object Example

public class ObjectExample {

public static void main(String[] args) {

new ClassInstantiatedAsObject();

}

}

Page 44: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries44

ObjectExample's main method is run and it creates an object of type ClassInstantiatedAsObject which means that ClassInstantiatedAsObject's

constructor (not main) is run

Page 45: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries45

Objects Unless explicitly defined otherwise,

any Java class can be instantiated

So if we changed ObjectExample to also create a ClassRunAsApp object...

public class ObjectExample {

public static void main(String[] args) {

new ClassInstantiatedAsObject();

new ClassRunAsApp();}

}

Page 46: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries46

2 objects are created and both constructors are run

Page 47: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries47

Objects How do I know the objects were

created?

In this case, there is no visual evidence of the object

Except that the text is displayed

That's because these were non-visual classes/objects

Page 48: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries48

Visual Objects Examples: all the GUI

components

Languages come with predefined classes for the GUI components

For instance, in Java, Frameimport java.awt.Frame;public class VisualObjExample {

public static void main(String[] args) {Frame frameVariable = new

Frame("FrameEx");frameVariable.setSize(200, 200);frameVariable.setLocation(500, 400);frameVariable.setVisible(true);

}}

Page 49: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries49

Visual Objects Again, notice the object is assigned to a variable

Variable must be same type as object

That's because we needed to change some of the object's attributes/properties These variables also called instance variables

In this case, changed/set the frame's Size, location and visibility

Page 50: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries50

Try it by downloading, compiling, running.Then change the size or location and run again.

Notice frame has setters – setSize, setLocation, etc.

Page 51: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries51

Object So the java rules for creating an

object are You create an object with the new

keyword To reference/use the object, it must

be assigned to a variable An object variable must be of the

same type as the object

The value of all the object's attributes/properties comprise its state

Page 52: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries52

Object Rules for executing an object method are: specify The variable name A period The method name Parenthesis

And any parameters to be passed• keyboard.getNextLine()

Why the variable name? There can be many objects of the

same type So, must specify which object

Page 53: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

Composition Exercise Assg3 Change Auto pseudocode so that:

The 3 global variables (make, model, and vin) have setters and getters

Solution

Page 54: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries54

OOP - Concepts Classes/objects can be related

two ways

Composition – one object has another object

Specialization – one object is another object

Aka inheritance

Both relationships allow one object to use another object's functions or attributes

Page 55: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries55

Composition An object can be composed of many other objects

A screen can be composed of Buttons, text fields, labels, strings, drop down menus, etc.

Doesn't have to just be a visual object to use composition An Invoice object could be composed of

Customer object Salesman object

Page 56: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries56

Composition The class that instantiates an object of another class is called the:

Class User or Class Client

So Invoice is a Client/User of Customer

Salesman

Page 57: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries57

Classes & Composition In Design All composition means is that the

class creates these objects Invoice is composed of Customer,

Salesman, and String objects

Simply create variables of the class types and assign the objects

Class InvoiceDeclare String invNum = New String("5d677as");Declare Customer invoiceCust = New Customer()Declare Salesman invoiceSalesMan = New Salesman()

End Class

Page 58: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries58

Specialization One class is a subclass (i.e. an extension, a type) of another class

ExitButton is a Button Salesman is an Employee

A subclass inherits all the attributes and methods of the superclass ExitButton gets all the attributes and methods of Button Same for Salesman and Employee

Page 59: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries59

Specialization This relationship demonstrates inheritance

The subclass inherits all the traits (attributes and methods) of the superclass

Why use? Faster to create a new subclass than define a new class

Quicker to create Salesman class if all functions and attributes of Employee are immediately included

Page 60: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries60

Specialization In Designs In class header, after the class

name add:

Extends Then the superclass name

Class SalesMan Extends Employee

blah, blah, blah

End Class

Page 61: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries61

Specialization Also, allows programmers to

easily enforce Polymorphism

Poly-what? Defining a standard interface for

similar classes

For instance, a salesman's salary is calculated as base Pay + bonusPct * weeklySales

But a Stock Room Attendant's is hoursWorked * hourlyRate

Page 62: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries62

Specialization/Inheritance However, Employee can specify that

all subclasses must have a method called calcPay() In java, calcPay() method defined as

abstract in Employee class

To compile, Salesman and StockRoomAttendant classes must have a calcPay() method

So the "same method" works differently for each class But the user of the classes only has to

remember one method name

Page 63: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

Person is a class

Name is a class

Person has a name object

Example

Person Namehas a

Class Person Declare Name personName = New Name()End Class

Page 64: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

Composition Example We’ll create classes called Name and Person

Name will have three properties First, Last, Middle

To create a property Create a Private variable Create a Public getter method to Return the variable value Create a Public setter method to change the variable value

Page 65: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

Specialization & Composition Ex Name is composed of 3 Strings

There is a "has a" relationship between Name and String Name "has a" first String Name "has a" middle String Name "has a" last String

Name has 3 Public getters & 3 Public setters that allow the class user to access the name properties

Page 66: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

Pseudocode Example

Class NameDeclare Private String firstDeclare Private String middleDeclare Private String last

Public Function String getFirst()Return first

End Function Public void setFirst(String f)

first = fEnd Module

Public Function String getMiddle()Return middle

End FunctionPublic setMiddle(String m)

middle = mEnd Module

Public Function String getLast()Return last

End Function Public setLast(String l)

last = lEnd Module

End Class

Page 67: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson IndustriesChapter 5 © copyright Janson Industries 2007 67

Inheritance Example// Name.java

public class Name extends Object {

private String first;private String last;private String middle;

public String getFirst() {return first; }

public void setFirst(String f) {this.first = f; }

public String getLast() {return last; }

public void setLast(String l) {this.last = l; }

public String getMiddle() {return middle; }

public void setMiddle(String m) {this.middle = m; }

}

Three Private String variables

Three setters and three getters

Java implementation

Page 68: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

Example Name needs a constructor

To make Name easier to use for its clients, will create three constructors

Null constructor Accepts nothing Does nothing

A constructor that accepts 2 strings

A constructor that accepts 3 strings

Page 69: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

Example Called method overloading

Methods with same name that have different parameter lists Another example of polymorphism! And another example of OOP advantages over procedural

• A procedural program can only accept one set of parameters• Would have to create many programs to accept different parameters

Page 70: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

Pseudocode ExamplePublic Module Name() End Module

Public Module Name(String f, String l)setFirst(f)setLast(l)

End Module

Public Module Name(String f, String l, String m) setFirst(f)setLast(l)setMiddle(m)

End Module

Null constructor

Accepts 2 strings and sets properties

Accepts 3 strings and sets properties

Notice the setters are used to change the attributes

Page 71: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

Example

public Name() {}

public Name(String f, String l) {this.setFirst(f);this.setLast(l);

}

public Name(String f, String l, String m) {this.setFirst(f);this.setLast(l);this.setMiddle(m);

}

Null constructor

Accepts 2 strings and sets properties

Accepts 3 strings and sets properties

Java implementation

Page 72: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

Example Person is going to be comprised of the following properties (attributes)

Birthday Name

Need Private variables to hold these values and getters and setters Person "has a" String (birthday) Person "has a" Name

Page 73: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries73

Class PersonDeclare Private String birthDayDeclare Private Name personName

Public Module Person() setBirthDay("")

End Module

Public Module Person(String bDay, String f, String l) setBirthDay(bDay)setPersonName(New Name(f, l))

End Module

Public Module Person(String bDay, String f, String l, String m) setBirthDay(bDay)setPersonName(New Name(f, l, m))

End Module

Three constructors

Pseudocode

Two Private variables

Page 74: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

Public Function String getBirthDay() Return birthDay End Function

Public Module setBirthDay(String bDay) birthDay = bDay

Return

Public Function Name getPersonName() Return personName End Function

Public Module setPersonName(Name name) personName = name

ReturnEnd Class

Two getters and two setters

Pseudocode

Page 75: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson IndustriesChapter 5 © copyright Janson Industries 2007 75

public class Person {private String birthDay;private Name name;

public Person() {this.setBirthDay("");}

public Person(String bDay, String f, String l) {this.setBirthDay(bDay);name = new Name(f, l);}

public Person(String bDay,String f, String l, String m) {

this.setBirthDay(bDay);name = new Name(f, l, m);}

public String getBirthDay() {return birthDay;}

public void setBirthDay(String bDay) {this.birthDay = bDay;}

public Name getName() {return name;}

public void setName(Name name) {this.name = name;}

}

Two Private variables

Two getters and two setters

Three constructors

Page 76: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

Exercise Assg 4 Change Auto pseudocode so it has three

constructors

Null constructor sets all properties to null (i.e. “”)

Constructor that accepts 2 strings Assigns strings to make and model, sets vin to

null

Constructor that accepts 3 strings Assigns strings to make, model and vin

Solution

Page 77: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

Example Why go to all the trouble to create Person and Name

Name will have some useful functions Like formatting the name based on whether 3 part name, 2 names and a middle initial

Right now if you try to print name or person you get a hashcode (memory location)

Page 78: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

Inheritance Example

For example, if we tried to "print a person object" as follows

public class PersonApp {

public static void main(String[] args) {Person personEx = new Person("01/01/1990",

"John", "Adams");System.out.println(personEx);

}}

Page 79: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries79

Huh? What's up with that?

Inheritance!

Page 80: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

ObjecttoString

PersontoString

NametoString

Though not explicitly coded both are subclasses of Object (Yes, there is a class called Object – DOH!)

is a is a

Inheritance/Specialization Example

Page 81: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

Inheritance Example And they inherit a method called toString

An object's toString method is called when System.out.println() tries to print the object

toString returns: The name of the class that the object was created from An @ symbol The hashcode (memory location) where the object resides

Page 82: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

Inheritance Example To get around this we will override the inherited toString method in Name and Person

Yes, you are not stuck with inherited methods and variables

You can override them by simply coding the method in the class Sort of like plastic surgery for your classes

If you don't like the nose you inherited – change it!

Page 83: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

Inheritance Example In Name add a nifty toString method that Returns the name

in different formats depending on whether its

A first and last name John Adams

A first, middle, and last name John Quincy Adams

A first name, middle initial, and last name John Q. Adams

Page 84: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

Inheritance Example Have a small problem

It is possible that a middle name String object was never created

I.e. one of the constructors only accepted first and last name

The middle String variable is considered null

Since it doesn’t point to an object

Public Name(String f, String l)setFirst(f)setLast(l)

Return

Page 85: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

public String toString() {String formattedName;try {

if (middle.equals(" "))formattedName = new String(first + " " + last);

else if (middle.length() == 1)formattedName = new String(first + " " + middle + ". " + last);

elseformattedName = new String(first + " " + middle + " " + last);

} catch (NullPointerException e) {formattedName = new String(first + " " + last);

}return formattedName;

}

Inheritance Example - Name Need Try/catch if middle never initialized

Page 86: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

public String toString() { return (name + " was born on " + birthDay);

}

Inheritance Example

We'll change Person so that it Returns Name Birth date Some descriptive text

Page 87: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries87

Page 88: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries88

Example Why create the class Name

Many classes use the same info and would want the formatting function

Person, Employee, Salesman, StockRoomAttendant, Customer, Supplier

Instead of coding in each class, use composition to include name in each

Even better use specialization Make Employee and Customer

subclasses of Person They will inherit name

Page 89: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

ObjecttoString

PersontoString birthDate name

is a is a

Specialization Example

CustomertoString birthDate name

EmployeetoString birthDate name

is a is a

NametoString

has a

Page 90: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

Inheritance Example We'll create Customer as a sub-

class of Person In pseudocode, use Extends

Notice: used setName (defined in Person) in Customer!

Class Customer Extends Person

Public Customer() Name custName = New Name(“George”,

“Washington”)setName(custName)

Return

End Class

Page 91: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

public class Customer extends Person{

public Customer() {this.setName(new Name("George",

"Washington"));this.setBirthDay("02/22/1732");

}}

Inheritance Example

We'll create Customer as a sub-class of Person

In java, use extends

Page 92: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

Public class PersonApp {

Public static void main(String[] args) { Person personEx = new Person("01/01/1990", "John", "Adams");

System.out.println(personEx);Customer cust = new Customer();System.out.println(cust);

}}

Inheritance Example We'll change PersonApp to

Create a Customer object

Print out the object

Page 93: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries93

WOW!

Page 94: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries94

Private and Inheritance Customer must use the inherited

setters to access the name and birthDate attributes because they are Private variables Only the Person class can access the

the private variables directly

Yes, even though Customer inherited these fields, it cannot access them directly

Page 95: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries95

Private and Inheritance Prove it: we'll try to set a value

directly and compile

public class CustTest extends Person{

public CustTest() {birthDay = "02/22/1732";

}}

Page 96: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries96

Inheritance Exercise Assg 5 Change design of Auto to include a

new property: numberOfDoors

Create pseudocode for 2 new subclasses of Auto called Sedan and Pickup

Create a Sedan property of trunkArea In constructor, numberOfDoors = 4

Create a Pickup property of flatBedArea In constructor, numberOfDoors = 2

Page 97: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries97

OOP Exercise Assg 6 Design a new program that

creates a Sedan object with the following properties Make is Honda Model is Accord Trunk area is 19

The app then displays the Make, model and number of doors

Assg 5 Solution, Assg 6 Solution

Page 98: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries98

Documentation With all the different ways classes

can be related, things get complicated

UML (Unified Modeling Language) comprised of many different diagrams showing class/method Structure Behavior Interaction

Page 99: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

Object

Person

Class Relationship Diagram

Customer Employee

Name

This type of class diagram shows specialization

Page 100: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries100

Class Relationship Diagram Assg 7 Create a class relationship diagram

showing the specialization relationship between Auto

Sedan

Pickup

Object

Solution Assg 7

Page 101: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

Class Diagram Example

Each class box can be expanded into three areas: Identification (name)

Attributes (variables)

Operations (methods)

Attributes and Operations can be further defined as Public, Private (+,-)

Name

- first:String- last:String- middle:String

+ Name()+ Name(f:String, l:String)+ Name(f:String, l:String, m:String)+ getFirst():String+ getLast():String+ getMiddle():String+ setFirst(f:String):void+ setLast(l:String):void+ setMiddle(m:String):void+ toString():String

Page 102: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

Class Diagram ExampleName

- first:String- last:String- middle:String

+ Name()+ Name(f:String, l:String)+ Name(f:String, l:String, m:String)+ getFirst():String+ getLast():String+ getMiddle():String+ setFirst(f:String):void+ setLast(l:String):void+ setMiddle(m:String):void+ toString():String

Attribute entries also specify the attribute’s type

The type is preceded by a colon & follows the attribute name

Operation entries specify the expected parameter(s)

These follow the operation name in parenthesis

Page 103: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

Class Diagram ExampleName

- first:String- last:String- middle:String

+ Name()+ Name(f:String, l:String)+ Name(f:String, l:String, m:String)+ getFirst():String+ getLast():String+ getMiddle():String+ setFirst(f:String):void+ setLast(l:String):void+ setMiddle(m:String):void+ toString():String

Operation entries also specify a Return value

The Return value is preceded by a colon & follows the expected parameters

Page 104: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries104

Class Diagram Exercise Create the class diagrams

showing the class Attributes

Operations

For Auto, Sedan, Pickup

Solution Assg 8

Page 105: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries105

UML Like structure diagram, gives an

overview

Does not show internal workings of the methods

So it is limited in usefulness when trying to understand how the class works

Page 106: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries106

Why OOP? Inheritance and composition

allow programmers to easily reuse code Faster to develop new programs

Reused code already tested and reliable

Easy to understand reused code

Page 107: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries107

Review Classes are the basis of OOP

An instance of a class is an object Object has unique values for the

class attributes (properties)

The constructor is the method that is executed when an object is created (instantiated)

Page 108: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries108

Review

Methods can be overloaded Makes class/object easier to use

Access specifiers allow data to be Private

Encapsulation is a technique to help with data integrity

Page 109: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries109

Graded Assignment 2 parts. A:

Design a class named GirlScout with properties of name troopNumber duesOwed

Create get and set methods for each field Include a static method called displayMotto that

displays “To obey the Girl Scout law”

Page 110: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries110

Graded Assignment A:

Include three overloaded constructors as follows: A default constructor that sets the name to “XXX”

and the numeric fields to 0 A constructor that allows you to pass values for

all three fields A constructor that allows you to pass a name and

troop number but sets dues owed to 0

Page 111: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries111

Graded Assignment A:

Create the GirlScout class diagram

Write the GirlScout pseudocode that defines the class

B: Create pseudocode for an app called GirlScoutApp that

Declares three GirlScout objects (and assigns them to variables named girl1, girl2, girl3) with these property values:

Page 112: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries112

Graded Assignment B:

“Shirley”, 123, 5.75 “Pam”, 321 No values

Display each GirlScout’s values

Display the motto

Page 113: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries113

Graded Assignment The output should look like the

following: Girl1 values:Shirley1235.75Girl2 values:Pam3210Girl3 values:XXX00To obey the Girl Scout law

Page 114: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries114

Graded Assignment Turn in as an email attachment

Class diagram of GirlScout

Pseudocode for GirlScout

Pseudocode for GirlScoutApp that performs the functions described

Page 115: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries115

OOP Example Enhanced PizzaApp XD

If 1 What would you like to order? Enter 1 for a soda Enter 2 for a pizza Enter 3 when finished ordering

What size soda would you like?Enter 1 for a 12 oz sodaEnter 2 for a 20 oz sodaEnter 3 for a 46 oz soda

Page 116: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries116

OOP Example Regardless of size, ask for flavor

Then back to main menu

What flavor soda would you like?Enter 1 for a cola sodaEnter 2 for a lemon/lime sodaEnter 3 for a cherry soda

What would you like to order? Enter 1 for a soda Enter 2 for a pizza Enter 3 when finished ordering

Page 117: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries117

OOP Example If 2

Ask for first toppingWhat size pizza would you like?Enter 1 for a 6 in pizzaEnter 2 for a 12 in pizzaEnter 3 for a 18 in pizza

What topping would you like on your pizza?Enter 1 for pepperoniEnter 2 for hamEnter 3 for mushroomsEnter 0 when done

Page 118: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries118

OOP Example Ask for another topping (maximum 10)

When 0, back to main menu

Would you like another topping?Enter 1 for pepperoniEnter 2 for hamEnter 3 for mushroomsEnter 0 when done

What would you like to order? Enter 1 for a soda Enter 2 for a pizza Enter 3 when finished ordering

Page 119: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries119

OOP Example When 3, print items ordered and total

The following items were ordered: 1 12 oz cola soda: 1.581 20 oz lemon/lime soda: 2.181 46 oz cherry soda: 2.781 12 oz lemon/lime soda: 1.581 6 in pizza with 1 topping(s): 7.231 12 in pizza with 2 topping(s): 11.481 18 in pizza with 3 topping(s): 16.73 For a total of: 4 soda(s) and 3 pizza(s) The order amount is $43.56

Page 120: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries120

OOP Example As I ruminate on the app

Will need sizes, flavors, toppings and prices constant information Will need selected sizes, flavors, toppings, prices for items ordered

Sounds like attributes/properties

What if each time a customer ordered a pizza or soda, a pizza or soda object was created As customer specifies, set the objects attributes to the customers selections

Page 121: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries121

OOP Example So when 1 entered

Soda object created

Size set

Flavor setWhat would you like to order? Enter 1 for a soda Enter 2 for a pizza Enter 3 when finished ordering1What size soda would you like?Enter 1 for a 12 oz sodaEnter 2 for a 20 oz sodaEnter 3 for a 46 oz soda2What flavor soda would you like?Enter 1 for a cola sodaEnter 2 for a lemon/lime sodaEnter 3 for a cherry soda

Page 122: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries 122

OOP Example Based on size the soda's price will be set

The soda object will be put in an array called orderedItems

$2.18

Page 123: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries123

OOP Example Same thing for pizza, pizza object created

Size set

But it will have toppings (in an array) instead of flavor and the price will have to be calculated

$10.23

Page 124: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries 124

OOP Example Pizza will be added to

orderedItems array

$2.18 $10.23

Page 125: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries 125

OOP Example As other items are ordered

they will be added to the array

$2.18$10.23 $5.98

$2.78

Page 126: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries126

OOP Example Then the list of items is displayed

with a total

The following items were ordered: 1 20 oz cola soda: 2.181 12 in pizza with 1 topping(s): 10.231 6 in pizza with 0 topping(s): 5.981 46 oz lemon/lime soda: 2.78 For a total of: 2 soda(s) and 2 pizza(s) The order amount is $21.17

Page 127: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries127

OOP Example Seems like pizza and soda have some attributes in common

Price

Size

Lists of prices and sizes Looks like a superclass could save some coding

What about common functions Calculate price based on soda size, pizza size, # of toppings

Page 128: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries128

OOP Example - Item Create a class called Item with

Attributes of name, price, size and numOfSizesPrices An array called sizes and an array called prices Setters and getters for all 6 variables One abstract method called calcPrice()

Abstract because will work differently for different items (i.e. soda vs. pizza) But all items will have a consistent interface called calcPrice()

Page 129: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

UML Example

Object

Item

Soda Pizza

Page 130: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

Item not too tough

Italics mean abstract

UML Example - Item

Item

- name:String - price:Real- prices:Real[] - size:String- sizes:String[] - prices:String[] - numOfSizesPrices:Integer

+ getName():String + setName(String):+ getSize():String + setSize(String):+ getPrice():Real + setPrice(Real):+ getNumOfSizesPrices():Real + setNumOfSizesPrices(Real):+ getSizes():String[] + setSizes(String[] ):+ getPrices():String[] + setPrices(Real[] ):+ calcPrice()

Page 131: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

Class Abstract ItemDeclare Private String name, sizeDeclare Private Real priceDeclare Private Integer numOfSizesPricesDeclare Private String sizes[]Declare Private Real prices[]

Public Module Abstract calcPrice()

Public String Function getName() Return Name

End Function

Public Module setName(String n) name = n

End Module

Public String Function getSize() Return size

End Function

Pseudocode Example - Item

Page 132: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

Public Module setSize(String s) size = s

End Module

Public Function Real getPrice() Return price

End Function

Public Module setPrice(Real p) price = p

End Module

Public Function Real getNumOfSizesPrices() Return numOfSizesPrices

End Function

Public Module setNumOfSizesPrices(Real num) numOfSizesPrices = num

End Module

Pseudocode Example - Item

Page 133: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

Public String[] Function getSizes() Return sizes

End Function

Public Module setSizes(String[] s) sizes = s

End Module

Public Function Real[] getPrices() Return prices

End Function

Public Module setPrices(Real[] p) price = p

End Module

End Class

Pseudocode Example - Item

Page 134: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

public abstract class Item {

private String name;private String size;private double price;private int numOfSizesPrices;private String[] sizes;private double[] prices;

public abstract void calcPrice();

public String getName() {return name;

}

public void setName(String n) {name = new String(n);

}

public String getSize() {return size;

}

Java Code Example - Item

Page 135: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

public void setSize(String s) {size = s;

}

public double getPrice() {return price;

}

public void setPrice(double p) {price = p;

}

public int getNumOfSizesPrices() {return numOfSizesPrices;

}

public void setNumOfSizesPrices(int num) {

numOfSizesPrices = num;}

public String[] getSizes() {return sizes;

}

Java Code Example - Item

Page 136: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

public void setSizes(String[] s) {sizes = s;

}

public double[] getPrices() {return prices;

}

public void setPrices(double[] p) {prices = p;

}}

Java Code Example - Item

Page 137: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries137

Example Create two subclasses of Item

called Pizza and Soda

In Soda, create attributes as follows An array called flavors

Variables called numOfFlavors and flavor

Page 138: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries138

Example In Soda, create setters and getters for

all attributes (declared or inherited) as follows

Set sizes to "12 oz", "20 oz", and "46 oz" Set prices to 1.58, 2.18, and 2.78 Set flavors to "cola", "lemon/lime", "cherry" Set name to "soda" Set numOfSizesPrices and numOfFlavors to

3 All other setters will expect the value to be

passed

Page 139: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries139

Example Have the constructor:

Call all the setters that set an attribute to a constant value

Have calcPrice() set the price value based on the size Find the size index number in the

size array Assign the same price array index

number value to price Using the price and size arrays as

parallel arrays

Page 140: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

Soda a little harder

UML Example - Soda

Soda

-- numOfFlavors:Integer - flavor:String-- flavors:String[]

+ Soda() + calcPrice(): + getNumOfFlavors():Integer + setNumOfFlavors(): + getFlavors():String[] + setFlavors(): + getFlavor():String + setFlavor(String): + setSodaSizes(): + setSodaPrices():

Page 141: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

Class Soda Extends ItemDeclare Private String flavors[]Declare Private String flavorDeclare Private Integer numOfFlavors

Public Soda() setName("soda")setNumOfSizesPrices(3)setNumOfFlavors()setFlavors()setSodaSizes()setSodaPrices()

Return

Public Integer Function getNumOfFlavors() Return numOfFlavors

End Function

Public Module setNumOfFlavors() numOfFlavors = 3

End Module

Pseudocode Example - Soda

Page 142: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

Public String[] getFlavors() Return flavors

End FunctionPublic Module setFlavors()

flavors = "cola", "lemon/lime", "cherry" End ModulePublic Module setSodaSizes()

Declare String[] sizes = "12 oz", "20 oz", "46 oz"

setSizes(sizes) End ModulePublic Module setSodaPrices()

Declare Real[] prices = 1.58, 2.18, 2.78setPrices(prices)

End ModulePublic Function String getFlavor()

Return flavorEnd FunctionPublic Module setFlavor(String flav)

flavor = flavEnd Module

12oz

20oz

46oz

sizes

1.58 2.18 2.78

prices

ParallelArrays

Page 143: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

Public Module calcPrice()Declare Integer i = 1Declare String[] sizes = getSizes()Declare real[] prices = getPrices()While (i <= getNumOfSizesPrices())

If (getSize() == sizes[i-1]) ThensetPrice(prices[i-1])

i++End While

End ModuleEnd Class

What's going on in the loop?

Pseudocode Example - Soda

Page 144: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries144

Java Code Example - Soda Ready to code?

Attributes defined Constructor sets constants

public class Soda extends Item {

private String[] flavors;private String flavor;private int numOfFlavors;

public Soda() {setName("soda");setNumOfSizesPrices(3);setNumOfFlavors();setFlavors();setSodaSizes();setSodaPrices();

}

Page 145: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries145

Java Code Example - Sodapublic int getNumOfFlavors() {

return numOfFlavors;}

public void setNumOfFlavors() {numOfFlavors = 3;

}

public void setFlavors() {flavors = new String[numOfFlavors];String flavor1 = new String("cola");String flavor2 = new

String("lemon/lime");String flavor3 = new String("cherry");flavors[0] = flavor1;flavors[1] = flavor2;flavors[2] = flavor3;

}

public String[] getFlavors() {return flavors;

}

Various setters and getters

Page 146: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries146

Java Code Example - Sodapublic void setSodaSizes() { String[] sizes = new

String[getNumOfSizesPrices()]; String size1 = new String("12 oz"); String size2 = new String("20 oz"); String size3 = new String("46 oz"); sizes[0] = size1; sizes[1] = size2; sizes[2] = size3; setSizes(sizes);}

public void setSodaPrices() { double[] prices = new

double[getNumOfSizesPrices()]; prices[0] = 1.58; prices[1] = 2.18; prices[2] = 2.78; setPrices(prices);}

Array setters

Page 147: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries147

Java Code Example - Sodapublic String getFlavor() {

return flavor;}

public void setFlavor(String flav) {flavor = flav;

}

public void calcPrice() {int i = 1;String[] sizes = getSizes();double[] prices = getPrices();while (i <= getNumOfSizesPrices()) {

if (getSize().equals(sizes[i - 1])) {setPrice(prices[i - 1]);

}i++;

}}

}

Rest of setters and getters

The piece de resistance

Page 148: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries148

Example - Pizza In Pizza, create:

Attributes called toppings and selectedToppings that are arrays

New attributes called toppingsCost, numOfToppings, and numOfToppingsSelected

In Pizza, create setters and getters for all arrays (declared or inherited) as follows: Sizes setter to initialize the array with

"6 in", "12 in", and "18 in"

Page 149: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries149

Example - Pizza Prices setter initializes the array to 5.98, 8.98,

and 12.98

Toppings setter initializes the array to "pepperoni", "ham", and "mushrooms"

Have setters that set toppingsCost to 1.25 numOfSizesPrices to 3 numOfToppings to 3

Have the constructor Call all the setters that set an attribute to a

constant value Have calcPrice set the price value based on

the size and toppings

Page 150: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

UML Example - Pizza

Pizza

-- numOfToppings:Integer - costOfToppings:Real-- toppings:String[] - selectedToppings:String[] -- numOfToppingsSelected:Integer

+ Pizza() + calcPrice(): + getNumOfToppings():Integer + setNumOfToppings():+ setPizzaSizes(): + getToppings():String[]+ setToppings(): + setPizzaPrices():+ getCostOfToppings():Integer + setCostOfToppings():+ getSelectedToppings():String[] + setSelectedToppings(String[]):- getNumOfToppingsSelected():Integer

Page 151: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

Class Pizza Extends Item

Declare Private String toppings[], selectedToppings[]Declare Private Integer numOfToppings,Declare Private Integer numOfToppingsSelected Declare Private Real costOfToppings

Public Module Pizza() setName("pizza" )setNumOfSizesPrices(3)setNumOfToppings()setCostOfToppings()setToppings()setPizzaPrices()setPizzaSizes()

End Module

Public Function Integer getNumOfToppingsSelected()Return numOfToppingsSelected

End Function

Public Function Integer getNumOfToppings()Return numOfToppings

End Function

Page 152: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

Public Module setNumOfToppings() numOfToppings = 3

End Module

Public Module setPizzaSizes() Declare String sizes[] = "6 in", "12 in", "18 in" setSizes(sizes)

End Module

Public Function String[] getToppings() Return toppings

End Function

Public Module setToppings() toppings[0] = "pepperoni" toppings[1] = "ham" toppings[2] = "mushrooms"

End Module

Public Module setPizzaPrices() Declare real[] prices = 5.98, 8.98, 12.98setPrices(prices)

End Module

Page 153: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

Public Function Integer getCostOfToppings() Return costOfToppings

End Function

Public Module setCostOfToppings() costOfToppings = 1.25

End Module

Public Function String[] getSelectedToppings() Return selectedToppings

End Function

Public Module setSelectedToppings(String[] selTops) selectedToppings = selTops

End Module

Pseudocode Example - Pizza

Page 154: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

Public Module calcPrice()Declare Integer i = 1Declare String[] sizes = getSizes()Declare real[] prices = getPrices()While (i <= getNumOfSizesPrices)

If (getSize = sizes[i-1]) Then setPrice(prices[i-1])

End Ifi++

End While Declare Integer numOfTopsSelected = 0While (selectedToppings[numOfTopsSelected] != "" AND numOfTopsSelected < 10)

numOfTopsSelected ++End While numOfToppingsSelected = numOfTopsSelected ;setPrice(getPrice() + numOfTopsSelected *

getCostOfToppings())End Module

End Class

Pizza calcPrice method works completely differently than Soda's

Page 155: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries155

Java Code Example - Pizzapublic class Pizza extends Item {

private String[] toppings, selectedToppings;private int numOfToppings, numOfToppingsSelected;private real costOfToppings;

public Pizza() {setName("pizza");setNumOfSizesPrices(3);setNumOfToppings();setCostOfToppings();setToppings();setPizzaPrices();setPizzaSizes();

}

public int getNumOfToppingsSelected() {return numOfToppingsSelected;

}

Page 156: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries156

Java Code Example - Pizzapublic int getNumOfToppings() { return numOfToppings;}public void setNumOfToppings() { numOfToppings = 3;}public void setPizzaSizes() { String[] sizes = new

String[getNumOfSizesPrices()]; String size1 = new String("6 in"); String size2 = new String("12 in"); String size3 = new String("18 in"); sizes[0] = size1; sizes[1] = size2; sizes[2] = size3; setSizes(sizes);}public String[] getToppings() {

return toppings;}

Page 157: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries157

Java Code Example - Pizzapublic void setToppings() { toppings = new String[numOfToppings]; String topping1 = new String("pepperoni"); String topping2 = new String("ham"); String topping3 = new String("mushrooms"); toppings[0] = topping1; toppings[1] = topping2; toppings[2] = topping3;}

public void setPizzaPrices() { double[] prices = new

double[getNumOfSizesPrices()]; prices[0] = 5.98; prices[1] = 8.98; prices[2] = 12.98; setPrices(prices);}

Page 158: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries158

Java Code Example - Pizza

public double getCostOfToppings() {return costOfToppings;

}

public void setCostOfToppings() {costOfToppings = 1.25;

}

public String[] getSelectedToppings() {return selectedToppings;

}

public void setSelectedToppings(String[] selTops) {selectedToppings = selTops;

}

Page 159: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries159

Java Code Example - Pizzapublic void calcPrice() {

int i = 1;String[] sizes = getSizes();double[] prices = getPrices();while (i <= getNumOfSizesPrices()) {

if (getSize() == sizes[i - 1]) {setPrice(prices[i - 1]);

}i++;

}int numOfTopsSelected = 0;while (selectedToppings[numOfTopsSelected] !=

null&& numOfTopsSelected < 10) {

numOfTopsSelected++;}numOfToppingsSelected = numOfTopsSelected;setPrice(getPrice() + numOfToppingsSelected *

getCostOfToppings());}

}

Page 160: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries160

Example - PizzaApp Now need an application that uses

Pizza and Soda objects App will display the UI

Main menu Pizza sizes Soda sizes Toppings Flavors

Will need an orderedItems array to hold pizza and soda objects (max 10)

Page 161: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries161

Example - PizzaApp If Soda

Creates soda object Get flavors array Displays flavors Reads flavor Sets flavor attribute Gets sizes array Displays sizes Reads size Sets size attribute Calls calculate price

Page 162: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries162

Example - PizzaApp If Pizza

Create pizza object

Get and display sizes, reads size, sets size attribute

Gets and displays toppings, reads topping, sets topping in selectedToppings array until done or 10 toppings

Calls calculate price

Page 163: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries163

Example- PizzaApp Adds the pizza or soda object to

the orderedItems array

After no more items or 10 items Display items and their costs

Gives a summary of number of sodas and pizzas ordered

Calculates total cost of items

Displays total cost of items

Page 164: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

Think I better start off with a structure chart

Get SodaInfo

Get UserResponse

Example

PizzaApp

Get ItemType

DisplayMain Menu

Get Size

GetFlavor

DisplaySize Menu

Get UserResponse

DisplayFlavors Menu

Get UserResponse

Page 165: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

DisplayTotals

CalcItem

Totals

Notice any duplication? Get user response

Get PizzaInfo

CalcTotals

Example - PizzaApp

Total

DisplayItems

Get Size

GetToppings

DisplaySize Menu

Get UserResponse

DisplayToppings

Menu

Get UserResponse

Calc $Total

Page 166: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries166

Example - PizzaApp The PizzaApp mainline is simply going to call the four major methods

What do we need in terms of variables for mainline An array to hold up to 10 items A numeric counter for the array A numeric variable to hold the user's input

Page 167: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries167

Example - PizzaApp Mainline will

Call getItem Which Returns the user's numeric response indicating Soda or Pizza

If 1, call getSoda If 2, call getPizza Both will Return either a Soda or Pizza object Load Returned item into array Do it again until 10 items or done Call calcTotal

Page 168: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

Module main()

Declare Private Item orderedItems[10] Declare Private Integer itemCtr = 0, inputNumeric = 1

While (inputNumeric < 3 AND inputNumeric > 0 AND itemCtr < 10)inputNumeric = getItem()If (inputNumeric = 1) Then

orderedItems[itemCtr] = getSodaOrder()Else

If (inputNumeric = 2) Then orderedItems[itemCtr] = getPizzaOrder()End If

End IfitemCtr++

End While

calcTotals(orderedItems)

End Module

Pseudocode Example - PizzaApp

Page 169: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

import java.util.Scanner;public class PizzaApp{ public static void main(String[] args) {

// Array and variables to hold ordered items, input and a counter

Item[] orderedItems = new Item[10];int itemCtr = 0;int inputNumeric = 1;

while (inputNumeric < 3 && inputNumeric > 0 && itemCtr < 10) {// Get type of item 1 for soda, 2 for pizza

inputNumeric = getItem();// Based on item get order particulars

if (inputNumeric == 1) {orderedItems[itemCtr] = getSodaOrder();

} else {if (inputNumeric == 2) {

orderedItems[itemCtr] = getPizzaOrder();}

}itemCtr++;

}calcTotal(orderedItems);

}

Java Example - PizzaApp

Page 170: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries170

Pseudocode Example - PizzaApp Will create two Private utility methods to

Display output

Get the user's input Which will Return the entered number

Private Module static Integer getInput()Declare Integer userInputInput userInputReturn userInput

End Module

Private Module static displayOutput(String s)Display(s)

End Module

Page 171: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

private static void displayOutput(String s) {// Prints out passed stringSystem.out.println(s);

}

private static int getInput() {int inputNumeric = 0;

// Variables and objects needed to read from command lineScanner keyboard = new Scanner(System.in);

// Retrieves inputinputNumeric = keyboard.nextInt();return inputNumeric;

}

Java Example - PizzaApp

Notice that the Scanner variable and object only created once in the

getInput methodSaved a lot of coding/debugging

Page 172: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries172

Pseudocode Example - PizzaApp getItem() will

Display the main menu Get the user's input using getInput()

Needs a variable to hold that value Return the user's input

Private Module static Integer getItem()Declare Integer inputNumericdisplayOutput ("")displayOutput ("What would you like to order? ")displayOutput ("Enter 1 for a soda ")displayOutput ("Enter 2 for a pizza")displayOutput ("Enter 3 when finished ordering ")inputNumeric = getInput()Return inputNumeric

End Module

What would you like to order? Enter 1 for a soda Enter 2 for a pizza Enter 3 when finished ordering

Page 173: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

private static int getItem() {

// Variable to hold users selection;int inputNumeric = 0;

// Prints out a blank line and instructiondisplayOutput(" ");displayOutput("What would you like to order? ");displayOutput("Enter 1 for a soda ");displayOutput("Enter 2 for a pizza ");displayOutput("Enter 3 when finished ordering ");

inputNumeric = getInput();

return inputNumeric;}

Java Example - PizzaAppJava code very close to pseudocode

Page 174: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries174

Pseudocode Example - PizzaApp getSoda() will

Create a soda object

Display the sizes available Need to get the sizes array from the soda object Need a variable for the array Need a counter for the array

Get the user's input using getInput() Needs a variable to hold that value

Set the size property in the soda object

What size soda would you like?Enter 1 for a 12 oz sodaEnter 2 for a 20 oz sodaEnter 3 for a 46 oz soda

Page 175: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries175

Pseudocode Example - PizzaApp getSoda() will

Display the flavors available Need to get the flavors array from the soda object Need a variable for the array

Get the user's input using getInput()

In the soda object Set the flavor property Calculate the soda price

Return the soda object

What flavor soda would you like?Enter 1 for a cola sodaEnter 2 for a lemon/lime sodaEnter 3 for a cherry soda

$2.18

Page 176: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

Private Module Soda getSoda()

Declare Private Soda soda = New Soda()Declare Private String sizes[], flavors[] Declare Private Integer ctr = 1, inputNumeric = 0

sizes = soda.getSizes()flavors = soda.getFlavors()

displayOutput("")displayOutput("What size soda would you like? ")While (ctr <= soda.getNumOfSizesPrices()) displayOutput("Enter ", ctr, " for a ", sizes[ctr-1], " soda") ctr++End WhileinputNumeric = getInput()

soda.setSize(sizes[inputNumeric - 1])ctr = 1

Pseudocode Example - PizzaApp

What size soda would you like?Enter 1 for a 12 oz sodaEnter 2 for a 20 oz sodaEnter 3 for a 46 oz soda

Page 177: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

displayOutput("") displayOutput("What flavor soda would you like? ")

While (ctr <= soda.getNumOfFlavors()) displayOutput ("Enter ", ctr, " for a ", flavors[ctr-1]," soda") ctr++ End While inputNumeric = getInput() soda.setFlavor(flavors[inputNumeric-1])

soda.calcPrice()

return soda

End Module

Pseudocode Example - PizzaApp

What flavor soda would you like?Enter 1 for a cola sodaEnter 2 for a lemon/lime sodaEnter 3 for a cherry soda

$2.18

Page 178: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

private static Soda getSodaOrder() {Soda soda = new Soda();int inputNumeric = 0;int ctr = 1;String[] sodaSizes = soda.getSizes();String[] sodaFlavors = soda.getFlavors();

// Prints out a blank line and gets soda sizedisplayOutput(" ");displayOutput("What size soda would you like?");while (ctr <= soda.getNumOfSizesPrices()) {

displayOutput("Enter " + ctr + " for a " + sodaSizes[ctr - 1] + " soda");

ctr++;}inputNumeric = getInput();soda.setSize(sodaSizes[inputNumeric - 1]);

ctr = 1;

Java Example - PizzaApp

Must reset ctr for flavors array

Finally a Soda object is created

Page 179: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

// Prints out a blank line and gets soda flavordisplayOutput(" ");displayOutput("What flavor soda would you like?");while (ctr <= soda.getNumOfFlavors()) {

displayOutput("Enter " + ctr + " for a " + sodaFlavors[ctr - 1] + " soda");

ctr++;}

// Get users selectioninputNumeric = getInput();

// Set the soda objects properties and return itsoda.setFlavor(sodaFlavors[inputNumeric - 1]);soda.calcPrice();return soda;

}

Java Example - PizzaApp

Page 180: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries180

Example - PizzaApp getPizza() will

Create a pizza object

Display the sizes available Need to get the sizes array from the pizza object Need a variable for the array Need a counter for the array

Get the user's input using getInput() Needs a variable to hold that value

Set the size property in the pizza object

What size pizza would you like?Enter 1 for a 6 in pizzaEnter 2 for a 12 in pizzaEnter 3 for a 18 in pizza

Page 181: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries181

Example - PizzaApp getPizza() will

Display the toppings available Need to get the toppings array from the pizza object Need a variable for the array Need an array to hold up to 10 toppings Need a variable for the array & ctr

Get the user's input using getInput() In the Pizza object

Set the selected toppings property Calculate the pizza price

Return the pizza object

What topping would you like on your pizza?Enter 1 for pepperoniEnter 2 for hamEnter 3 for mushroomsEnter 0 when done

$10.23

Page 182: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

Private Module static Pizza getPizza()

Declare Private Pizza pizza = New Pizza() Declare Private String sizes[], toppings[], selectedToppings[] Declare Private Integer ctr = 1, inputNumeric = 0, toppingsCtr = 0

sizes = pizza.getSizes() toppings = pizza.getToppings()

displayOutput("") displayOutput("What size pizza would you like? ") While (ctr <= pizza.getNumOfSizesPrices()) displayOutput("Enter ", ctr, " for a ", sizes[ctr-1], " pizza ") itemCtr++ End While inputNumeric = getInput()

pizza.setSize(sizes[inputNumeric -1])

ctr = 1

Pseudocode Example - PizzaApp

What size pizza would you like?Enter 1 for a 6 in pizzaEnter 2 for a 12 in pizzaEnter 3 for a 18 in pizza

Page 183: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

displayOutput("") displayOutput("What topping would you like on your pizza? ") While (ctr <= pizza.getNumOfToppings()) displayOutput ("Enter ", ctr, " for ", toppings[ctr-1]) ctr++ End While displayOutput("Enter 0 when done")

inputNumeric = getInput()

While(inputNumeric != 0 AND toppingsCtr < 10) selectedToppings[toppingsCtr] = toppings[inputNumeric - 1] toppingsCtr ++

ctr = 1

displayOutput("Would you like another topping? ") While (ctr <= pizza.getNumOfToppings()) displayOutput ("Enter ", ctr, " for ", toppings[ctr-1]) ctr++ End While displayOutput("Enter 0 when done") inputNumeric = getInput() End While

Priming write for toppings

Store selected topping, ask for up to 9 more

What topping would you like on your pizza?Enter 1 for pepperoniEnter 2 for hamEnter 3 for mushroomsEnter 0 when done

Page 184: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

pizza.setSelectedToppings(selectedToppings) pizza.calcPrice()

Return pizza

End Module

Pseudocode Example - PizzaApp Finish up by

Setting the toppings property in the pizza object

Calculating the pizza objects price

Return the pizza object

$10.23

Page 185: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

private static Pizza getPizzaOrder() {Pizza pizza = new Pizza();int inputNumeric = 0;int ctr = 1;int toppingsCtr = 0;String[] pizzaSizes = pizza.getSizes();String[] pizzaToppings = pizza.getToppings();String[] selectedToppings = new String[10];

// Prints out a blank line and gets pizza sizedisplayOutput(" ");displayOutput("What size pizza would you like?");while (ctr <= pizza.getNumOfSizesPrices()) {

displayOutput("Enter " + ctr + " for a " +pizzaSizes[ctr - 1] + " pizza");

ctr++;}

inputNumeric = getInput();pizza.setSize(pizzaSizes[inputNumeric - 1]);ctr = 1;

Java Example - PizzaApp

Very similar to getSoda

Page 186: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

// Prints out a blank line and gets toppings, max of 10displayOutput(" ");displayOutput("What topping would you like on your

pizza?");while (ctr <= pizza.getNumOfToppings()) {

displayOutput("Enter " + ctr + " for " + pizzaToppings[ctr - 1]);

ctr++;}displayOutput("Enter 0 when done");

inputNumeric = getInput();while (inputNumeric != 0 && toppingsCtr < 10) {

selectedToppings[toppingsCtr] = pizzaToppings[inputNumeric - 1];

toppingsCtr++;ctr = 1;displayOutput("Would you like another topping?");while (ctr <= pizza.getNumOfToppings()) {

displayOutput("Enter " + ctr + " for " + pizzaToppings[ctr - 1]);

ctr++;}

Java Example Toppings more complicated than flavors cause there can be up to 10

Page 187: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

displayOutput("Enter 0 when done");inputNumeric = getInput();

}

pizza.setSelectedToppings(selectedToppings);pizza.calcPrice();

Return pizza;}

Java Example - PizzaApp

Page 188: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries188

Example - PizzaApp calcTotal(Item itemsOrdered[]) will

Display each item description and cost Need a ctr variable for the array Need a pizza and soda variable to assign the array items to

Keep a count of the number of pizzas and sodas Need variables to hold those values

Calculate the total cost and display Need a variable for the value

Page 189: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

Module Private static calcTotal(Item itemsOrder[] )

Declare Private Pizza pizza Declare Private Soda soda Declare Private Integer ctr = 1, pizzaCtr = 0, sodaCtr = 0, orderTotal = 0

displayOutput("The following items were ordered: ")//Read item array, display each item, count sodas, pizzas & calc total While (ctr <= 10)

If (itemsOrder[ctr-1] == pizzaObject) Thenpizza = itemsOrder[ctr-1]displayOutput("1 ", pizza.getSize(), " ",

pizza.getName() + " with ", pizza.getNumOfToppingsSelected(),

" topping(s): " + pizza.getPrice())orderTotal = orderTotal + pizza.getPrice()pizzaCtr++

End If

Pseudocode Example - PizzaApp

Page 190: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

If (itemsOrder[ctr-1] == sodaObject) Thensoda = itemsOrder[ctr-1]displayOutput("1 ", soda.getSize(), " ",

soda.getFlavor()," ", soda.getName(), ": ", soda.getPrice())

orderTotal = orderTotal + soda.getPrice()sodaCtr++

End Ifctr++

End While

displayOutput(" ")displayOutput("For a total of: ")displayOutput(sodaCtr, " soda(s) and ", pizzaCtr, " pizza(s)")displayOutput(" ")displayOutput("The order amount is $" + orderTotal)

End Module

Pseudocode Example - PizzaApp

Page 191: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

private static void calcTotal(Item[] itemsOrdered) {int ctr = 1, pizzaCtr = 0, sodaCtr = 0;Pizza pizza;Soda soda;double orderTotal = 0;

displayOutput("The following items were ordered: ");while (ctr <= 10) {

if (itemsOrdered[ctr - 1] instanceof Pizza) {pizza = (Pizza) itemsOrdered[ctr - 1]; displayOutput("1 " + pizza.getSize() + " "+ pizza.getName() + " with "+ pizza.getNumOfToppingsSelected() + " topping(s): " + pizza.getPrice());orderTotal = orderTotal + pizza.getPrice();pizzaCtr++;

}if (itemsOrdered[ctr - 1] instanceof Soda) {

soda = (Soda) itemsOrdered[ctr - 1]; displayOutput("1 " + soda.getSize() + " "+ soda.getFlavor() + " " + soda.getName() +

": "+ soda.getPrice());orderTotal = orderTotal + soda.getPrice();sodaCtr++;

}

Page 192: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries

ctr++;}

// Round off the order totalint orderTotalInt = (int) ((orderTotal + .005) * 100);orderTotal = orderTotalInt;orderTotal = orderTotal / 100;

// Print out the order totaldisplayOutput(" ");displayOutput("For a total of: ");displayOutput(sodaCtr + " soda(s) and " + pizzaCtr

+ " pizza(s)");displayOutput(" ");displayOutput("The order amount is $" + orderTotal);

}}

Java Example - PizzaApp

Page 193: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries193

Set up the environment

First compile the superclasses then the subclasses

then the using classes

Run the app

PizzaApp In Action

Page 194: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries194

PizzaApp In Action

Put in the item(s)

Page 195: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries195

PizzaApp In Action

Enter 3 to finish

Individual items displayed

Total info displayed

All these classes are on the class website (not BB)

Page 196: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries196

Points to Remember Classes are the basis for creating

objects Objects are instances of classes

Each object can have unique values for its properties

Properties (aka attributes) are Private variables The have getter/setter methods to

access their values This is an example of encapsulation

Page 197: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries197

Points to Remember When object created the

constructor method is run Constructor has same name as class

but returns nothing

Methods can be overloaded

Same name, different signature

Makes class easier to use

Constructors can be overloaded

Page 198: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries198

Points To Remember Classes can be related through

Specialization Forms a is-a relationship

• Pizza is an Item, Soda is an Item Composition

Forms a has-a relationship• Pizza has an Integer array, a String, etc.

Both allow a class to access the methods and properties of other prewritten classes

Faster development Fewer errors More reliable

Page 199: 1 Intro to Programming & Algorithm Design Object Oriented Programming Copyright 2003 by Janson Industries This presentation can be viewed on line in a

Copyright 2015 by Janson Industries199

Points To Remember Access to methods and variables can

be restricted by access specifiers/modifiers

Public: any class can access

Private: can only be accessed from within the class