CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World...

130
CS121/IS223 Week 9, Slide 1 CS121: Computer Programming I Object-Oriented Primer Dr Olly Gotel [email protected] http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors

Transcript of CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World...

Page 1: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 1

CS121: Computer Programming I

Object-Oriented Primer

Dr Olly Gotel [email protected] http://csis.pace.edu/~ogotel

Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors

Page 2: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 2

Brain Re-Wiring Time

Page 3: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 3

Agenda

•  Many ways to tackle a problem…

•  Design example and important design concepts

•  Exercise -- OO design -- thinking with objects

•  Important object-oriented (OO) concepts

•  Role-playing demo to illustrate some of these concepts by simulating OO program execution (maybe in a couple of weeks)

•  Revisiting methods and re-looking at classes …

Page 4: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 4

How to Tackle a Problem?

•  Decomposition - handling complexity by the principle of “divide & conquer”

•  Two forms of decomposition –  Process-oriented: according to

steps or functions –  Object-oriented: according to behaviour of

autonomous objects

•  Both valid, but current claims for superiority of OO –  Stronger framework, reuse of common

abstractions & resilient under change

Tends to involve constructing hierarchies

Page 5: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 5

Get Transaction

2 Types of Decomposition

Transaction

Open Withdraw

Passbook Open

Checking Open

Bonus Open

Passbook Withdraw

Checking Withdraw

Bonus Withdraw

Passbook Deposit

Checking Deposit

Bonus Deposit

Deposit

Open Deposit

Withdraw Account

ihs ihs ihs

Passbook Account Checking

Account Bonus Account

Other object(s)

Page 6: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 6

Making Changes - which localises change?

Transaction

Get Transaction

Open

Deposit

The image cannot be displayed. Your computer may not have enough memory to open

Loadsadosh Deposit

The image cannot be displayed. Your computer may not have enough memory to open

Loadsadosh Withdraw

The image cannot be displayed. Your computer may not have enough memory to open

Loadsadosh Open

The image cannot be displayed. Your computer may not have Withdraw

The image cannot be displayed. Your computer may not have enough Deposit

Open Deposit

Withdraw Account

ihs ihs ihs

Passbook Account Checking

Account

ihs Other object(s)

Loadsadosh Account

Bonus Account

Passbook Open

Checking Open

Bonus Open

The image cannot be displayed. Your computer may not have enough

Open

Passbook Deposit

Checking Deposit

Bonus Deposit

Passbook Withdraw

Checking Withdraw

Bonus Withdraw

Page 7: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 7

Design Example - starting object think

•  A conceptual design for a small, one-branch bank

•  The whole thing, not just the computer part

•  What are the THINGS?

•  What can they do?

•  Think - how would someone on the street RECOGNISE this as a small bank?

Page 8: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 8

Design Example

•  A simple design for a small one-branch bank

[Sample solution from Cockburn 1998]

No right or wrong here!

Page 9: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 9

Design Concepts

•  Items required for “good” design [Cockburn 1998]:

–  Name of key components, or things, in the system

–  Purpose, basic function, or main *responsibility* of each thing

–  Key communication paths between them

–  List of the services provided

Page 10: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 10

CRC Cards

Vault

Holds the money Teller

What it does

What it interacts with

What it is called

Page 11: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 11

CRC Cards - use them to think!

Class name

Responsibilities (i.e. services it provides)

Collaborators (i.e. other classes this class relies on for services)

What it does

What it uses

What it is called

Page 12: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 12

Exercise – Thinking With Objects

You are contractors who just won a bid to design a custom coffee vending machine for the employees of Acme Works to use. Arnold, the owner, wants his own, custom design. He is, however, a cheapskate. Arnold tells us he wants a simple machine. All he wants is a machine that serves coffee for 35 cents, with or without sugar & creamer. He expects you to be able to put this little machine together quickly & for little cost

You get together & decide there will be a coin slot & coin return, coin return button, & four other buttons: black, white, black with sugar, & white with sugar

Source: [Cockburn 1988]

STEP 1

Page 13: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 13

Design the Coffee Machine Using Objects

•  What are the components?

•  What are their responsibilities?

•  Which components rely on which other components for services?

•  How do they work together to deliver the simple service: give coffee for 35 cents?

•  Which component knows the price of the drink?

•  Which component knows how to make the drink?

•  Run some scenarios – does it work?

•  Draw this!

Create the CRC cards for these

Enact the CRC cards

Page 14: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 14

Candidate Design 1

[Sample solution from Cockburn 1998]

Page 15: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 15

Interaction Diagram for Design 1

[Cockburn 1998]

Page 16: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 16

Does Your Design Support Change?

•  After 5 machines are installed & have been operating for a while, Arnold comes along & says, "I would like to add bouillon, at twenty-five cents. Change the design."

•  You add one more button for bouillon & one more container for bouillon powder

•  How else do you change your design?

STEP 2

Page 17: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 17

Candidate Design 2

[Sample solution from Cockburn 1998]

Page 18: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 18

Interaction Diagram for Design 2

[Cockburn 1998]

Page 19: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 19

Analysis of Designs 1 & 2

•  Design to localise change

•  Beware of “super” components – distribute the responsibilities

•  Create some CRC cards to help you check that your design works by running some scenarios of use

•  List as many other changes & additions you believe Arnold may ask you to make in the future

Page 20: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 20

Yet Another Change!

•  Arnold comes back with a brilliant idea. He has heard that some companies use their company badges to directly debit the cost of coffee purchases from their employees' paychecks. Since his employees already have badges, he thinks this should be a simple change.

•  You add a badge reader & link to a payroll system

•  What else?

STEP 3

Page 21: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 21

Candidate Design 3

[Sample solution from Cockburn 1998]

Page 22: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 22

Move Over Starbucks!

•  People are starting to buy Starbucks lattes instead of Arnold's coffees. So Arnold wants the machine modified just slightly, so that he can create a "drink of the week." He wants to be able to add new drinks and change prices any time, to match his competition. He wants to be able to add espresso, cappuccino, hot chocolate, latte, choco-latte, steamed mil, soy chai — in short, anything he can mix together. You add a couple more buttons, a milk steamer & dispenser, & some more powder dispensers. You need a really good, robust design, so that you or Arnold can change the products & prices at will, without tearing the machine apart any further.

STEP 4

Page 23: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 23

Candidate Design 4

[Sample solution from Cockburn 1998]

Page 24: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 24

Interaction Diagram for Design 4

[Cockburn 1998]

Page 25: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 25

Reference for Design Exercise

•  Read all about it! On my web-site

•  Object-Oriented Analysis & Design, Parts 1 & 2, Alistair Cockburn, CUJ, May & June 1998: –  http://www.cuj.com/documents/s=8065

/cuj9805cockburn/ –  http://www.cuj.com/documents/s=8064

/cuj9806cockburn/

Recommended

Page 26: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 26

Good Design Takes Time

•  Simple

•  Supports easy change

•  Uses abstractions from the domain

•  Satisfies the need today & tomorrow!

Rare to get it perfectly the first time – you must be prepared to learn and iterate

Page 27: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 27

Classes, Objects & Methods

(Message.java)

public class Message{

}

public class MessageMaker{

public static void main(String[] args) { Message myMessage = new Message(); myMessage.printMessage(); myMessage.changeMessage(“goodbye”); myMessage.printMessage(); }}

public void printMessage() { System.out.println(m); }

Other methods here

C-class; R-methods; C-method calls

private String m = “hello”;

public void changeMessage (String newMessage) { m = newMessage; }

Page 28: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 28

Hello World in Java (Non-OO)

// Another Hello World Program –

// HelloAgain.java

public class HelloAgain

{

public static void main(String[] args) {

System.out.println("Hello World!");

} }

MUST call this file HelloAgain.java

Must name the file after this

REMEMBER THIS?

Page 29: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 29

Hello World in Java (OO)

// Yet Another Hello World Program // HelloWorld.java public class HelloWorld { public static void main(String[] args) { Hello hello = new Hello(); hello.printHello(); } }

// A Hello class for Yet Another Hello World Program // Hello.java public class Hello { public void printHello() { System.out.println("Hello World!"); } }

Must call this file HelloWorld.java

MUST call this file Hello.java

TRY THIS NOW!!!

Page 30: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 30

Object-Oriented Concepts

•  Classes •  Objects •  Methods •  Messages & message passing •  Parameters & arguments •  Return types & voids •  Encapsulation & information hiding •  Instance variables & class variables •  State •  Access modifiers •  Overriding & overloading* •  Interfaces* •  Inheritance* •  Polymorphism* •  …* later

} We we will look at these in detail and look more at the other concepts in the follow-up course

Page 31: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 31

Next Few Weeks: what they mean & how to use!

object

class

encapsulation

polymorphism

inheritance message passing

interface

attribute

dynamic binding

state

behaviour

identity

abstraction

method instance

message

relationship

generalisation & specialisation

Page 32: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 32

Role-playing Demo

© http://www.ridgecrest.ca.us/~curtdan/TREK/TAS.cgi?FILE=Larson

At some point…

How an OO program works - to illustrate concepts in everyday terms

Page 33: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 33

In Plain Terms, an Object is …

•  Something that represents an atomic entity

•  Something you can uniquely identify (identity)

•  Something that encapsulates data as its state

•  Something you can send messages to, causing it to respond/behave in some way

•  Something whose behaviour depends on its internal state (which may change)

•  Has a public interface & private internals

object state behaviour identity has + +

Page 34: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 34

Example Objects

•  Passive objects –  One loaf of bread –  One packet of herbal tea –  Invoice 63501 sent to A Farm, Malvern

•  Active objects –  Lorry "M235 BCM“; Van "N683 CNM" –  Fax machine in Richard Green's office

•  Human agents –  Richard Green; David Brown (Executive)

•  Structure objects –  Marketing Department

object

Page 35: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 35

•  Gordon, Junior Librarian, as object

Attributes Name: Gordon Position: Junior Librarian Age: 25 Salary: 12,000 ......

Relations Supervisor

Operations Loan out books Rename position Amend salary

M T W T F

Looking Inside an Object

object state behaviour identity has + +

Page 36: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 36

State

•  All the data the object currently encapsulates

•  Data is defined in terms of valued attributes (characteristic features - name / value pairs)

•  The value of some attributes is fixed (immutable)

•  The value of some attributes can change (mutable)

•  Values of the attributes are the state of the object

state

student_id; registered_courses; weight; date_of_birth

attribute

Page 37: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 37

Identity

•  Attribute values may change, so don’t clearly pin-point the object over time

•  Identity makes it possible to distinguish any object in an unambiguous way & independent from its state

•  Characterises the object to give persistence

•  Like a “natural key” or unique handle

identity

phone number student_id

Page 38: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 38

Behaviour

•  Operations enable an object to act & react

•  Objects can receive certain messages & act upon them

•  The set of messages the object can understand is generally fixed & defined in its interface

•  Reaction to messages may depend on current attribute values (i.e. state); it may even change the state

behaviour

on off flickSwitch

Page 39: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 39

Message

•  Messages are sent to objects to trigger behaviour

•  Structure - keyword selector & optional arguments

•  Arguments are values being passed to the object

•  Object may respond to a message by sending a message to another object!

message

Identity: myClock Attribute: currentTime Message: resetTime(newTime) Message: tellTime

Page 40: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 40

Message Passing

•  Objects therefore interact by passing messages to one another (i.e. object interaction)

•  A message requests an object to perform an operation or service

•  A message consists of a name & any arguments

message passing

The imag

1

2

3

4

Page 41: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 41

Interface

•  An object can have public & private interface

•  An object’s public interface defines the messages it will accept & that all can use

•  An object’s private interface can only be used by the object itself or those who are privileged

•  Structure - selector, required arguments & what will be returned

interface

public -> resetTime(newTime: Time) public -> tellTime() : Time private -> time : Time

Page 42: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 42

Method

•  A description that determines how an object reacts to a message (e.g. a piece of code to implement the operation)

•  Methods are called in response to messages sent to objects

•  The operation performed is determined by the the object’s class & the value of the object’s attributes - so the method has full access to the object’s state

•  Matching a message name to a method is called binding

method

Page 43: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 43

Dynamic binding

•  The same message can be sent to different objects

•  Each object can bind the message to a different method, as defined by its class

•  Dynamic (late) binding refers to the process of identifying what code should be executed as the result of receiving a message

•  Reduces coupling between objects

•  Enables pluggability & substitutability

dynamic binding

Page 44: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 44

Encapsulation

•  Behaviour & information are encapsulated in objects (we say objects are strongly encapsulated)

•  From outside, an object can only be manipulated via its public interface; the internal state is private & can only be changed by the object itself

•  Other objects can only know operations on the object, not how they work

•  Necessary prerequisite for information hiding & programming by contract

encapsulation

Page 45: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 45

Class

•  Objects can have a lot in common & can lead to much duplication

•  A class defines the structure & behaviour of a particular kind of object - acting as a template or blueprint

•  Classes represent groups of objects with the same behaviour & information structures

•  Every object belongs to a class (i.e. is an instance of a single class), though a class may have many instance objects

class

student

ann jo

?timepiece?

Classes represent abstractions

Page 46: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 46

Class (in UML)

Book

title: String

copiesOnShelf(): int borrow(c:Copy)

Class name

Name

Type

Parameters & their types

Name compartment

Instance variables

Method definitions

}

}

}

Return type

class

•  We call this representation of a book an abstraction

Page 47: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 47

Instance & Instantiation

•  Instantiation - the process of creating a new object belonging to a class

•  Instance - the resulting object

•  Note that this object is a new “thing” with its own identity

•  The state of the new object must be initialised (i.e. its instance variables given values)

instance

Attributes

Registration No. Weight Fuel

Driver Trailer

Operations

Deliveries Goods Refuel

Truck

Relations

Create (Truck)

Delete (Truck)

Values will differ @ instance level

Page 48: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 48

Classes & Objects

•  Classes define structure & behaviour of a system

•  Objects represent the *actual* system

classes

objects

relationships

links

Page 49: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 49

Key Points

•  You can approach a problem in different ways: –  Procedurally, by breaking a problem down into

smaller problems that compose to solve the overall problem (you create a tree)

–  Using communicating objects (you create a network)

•  OO design is natural & scaleable, but requires thinking with objects, being prepared to iterate & giving up the notion of global control

•  OO programming concepts support this way of thinking & solving problems

Page 50: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 50

Coming Up Next

•  Banks, coffee machines & trek species are all objects – before we look at how to define them (using classes) & create instances (objects), we will look at communication between objects & the services they provide (methods)

•  Java – how it deals with classes, objects & methods … starting with methods again … programming the OO way (you need to have done your prep work!)

•  What is really going on? Program control flow

Page 51: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 51

Agenda

•  How to define & use simple classes (with instance variables & methods) – may be new

•  How to create instances of classes (objects) – & what are these things anyway? – may be new

•  How to define & use methods (should be a recap – so go through these slides at home for homework): –  main method & constructors –  Parameters/arguments & returns –  Visibility (access modifiers) –  Method overloading

Page 52: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 52

Java Ingredients So Far

•  Variables, assignment, operators… •  Expressions, statements, compound statements… •  Control structures – selection, iteration… •  Lots of other useful bits & pieces along the way –

arrays, files, etc

•  Aim now – to write OO programs

•  Need - to create your own objects, which means writing your own class types

•  One step at a time…

Page 53: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 53

How to Write an OO Program in Java (Simplified)

•  Identify classes needed

•  Identify methods & variables needed by objects of those classes

•  Write classes

•  Run program by creating objects in a main method (often in a driver class) & calling the object’s methods

•  Objects then call each other’s methods

Page 54: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 54

Reminder

•  Class: template for creating objects of a particular type, defining data about the objects (instance variables) & operations they can carry out (methods)

•  Object: instance of a class, given a name & actual data values – it can carry out the operations

•  Methods are the building block of OOP – they should be small, cohesive & general-purpose

KEY WORD Encapsulation: combination of data & operations in a single self-contained object

Page 55: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 55

Classes & Methods … & Objects

public class ExampleClass{

public void methodOne(){ Statements…

}

public void methodTwo(){

Statements…

} }

ExampleClass myObj = new ExampleClass(); myObj.methodOne(); myObj.methodTwo();

A class can declare a number of methods

Methods are called on instance objects of the class

Instance object created

Constructor

Page 56: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 56

Written a Method, How Do You Use It?

•  Methods are called on objects – but when you start a program running, you have no objects

•  Remember the main method:

public static void main(String[] args) { }

•  main creates object(s) & calls their methods – the objects then take over the show main is special – write no other static methods on this course

Means method does NOT need to be called on an object

Page 57: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 57

Classes

•  Class name: Car

•  Data: –  Colour –  Licence –  Speed –  Fuel

•  Methods: –  Accelerate –  Brake

Colour: orange Licence: J342 Speed: 20 mph Fuel: 2 gallons

Colour: red Licence: RACER Speed: 100 mph Fuel: 15 gallons

A class is a data type

Page 58: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 58

Car

-  colour: string -  licence: string -  speed: double -  fuel: double

+ accelerate(double mss, double t): void + brake(double mss, double t): void + honk(): void

The Same Information in UML

•  Unified Modelling Language – a class diagram

Class name

Data

Methods

Page 59: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 59

Classes & Objects

Car

-  colour: string -  licence: string -  speed: double -  fuel: double

+ accelerate(double mss, double t): void + brake(double mss, double t): void + honk(): void

One class, many objects

Page 60: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 60

Writing the Java Class Definition

•  Each Java class definition should be stored in its own file (filename the same as class name, with .java extension – just as you have been doing) – e.g. Car.java

•  Your program can have many classes (so many files), but only one has a main method amongst them

•  It is a good idea to put this in a driver or test class

•  Put all your classes in the same directory for now

Page 61: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 61

Write the Classes

public class Car{ private String colour, licence; private double speed, fuel;

public void honk(){ System.out.println(“Beep Beep!”); } }

public class CarTester{ public static void main(String[] args){ Car myCar = new Car(); myCar.honk(); } }

Instance variables – private means can only be changed inside the class (by its methods)

Method – public means that it can be called from outside the class by objects of Car class

Primary class

Test class with main() method

Make a new car object & call it myCar

Get myCar to honk its horn

Page 62: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 62

Car Race

Page 63: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 63

Objects & Classes

•  Object: –  distinguishing characteristics –  data associated with it (attributes or instance

variables) –  can perform certain actions (methods)

•  Class: –  defines a type of object –  the blueprint/template/definition

•  Examples of objects & classes?

Page 64: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 64

Methods

•  Can structure programs as a collection of methods that call one another

•  Methods help to organise code - they should be small, cohesive & general-purpose

•  Methods can have parameters & so take arguments – this makes them more general-purpose

•  Methods can return values (or void)

•  Your program always has ONE main method & this is where execution starts

Page 65: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 65

From Procedural to OO Programming (OOP)

•  Before: –  all code was in a class that you gave the same name as your file –  all the class code was inside a main method –  this code was executed in sequential manner

•  Now: –  still can have a single class / file – for hybrid –  code in the main method creates an object of the class type, then

calls its methods (i.e. tells it to do things) –  the “doing” code is packaged into named methods –  no longer any sequence as such – more interesting

A program was a sequence of statements

A program is a collection of method-calling objects

Page 66: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 66

Onward to OO…

•  You can approach a problem in different ways: –  Procedurally, by breaking a problem down into

smaller problems that compose to solve the overall problem (you create a tree)

–  Using communicating objects (you create a network)

•  OO design is natural & scaleable, but requires thinking with objects & being prepared to iterate to improve your thinking

•  OO programming concepts support this way of thinking & solving problems

Page 67: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 67

Benefit of Programming this Way?

Page 68: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 68

Key Points

•  Class: template for creating objects of a particular type, defining data about the objects (instance variables) & operations they can carry out (methods)

•  Object: instance of a class, given a name & actual data values – it can carry out the operations

•  Methods are the building block of OOP – they should be small, cohesive & general-purpose

KEY WORD Encapsulation: combination of data & operations in a single self-contained object

Page 69: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 69

EXTRA SLIDES TO DIGEST @ HOME

A Quick Reminder on Methods

Go through this material again (presented earlier in the course) and see if you can try a few things out in code, coupled with support from your text book

Page 70: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 70

Writing Java Programs

•  Only written very small programs to date using one class (the name of your program) – OO, but not really OO

•  How do you write really BIG programs? How do you write OO ones?

•  One big class, with lots of statements, loops & selections inside? –  repeats bits of code –  jumps all over the place

•  It would just be a mess – needs structure

How do your programs work?

Page 71: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 71

Helping With Digestion

•  Which is easier to talk about or refer to: –  a sandwich, a packet of chips, a cookie, some

fruit, a carton of juice? –  a box lunch?

•  Package stuff up and give it a label to refer to!

Page 72: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 72

Organising Code

•  We group programming statements to make the task of programming more comprehensible

•  Statements are generally grouped when, together, they perform some task

•  A name is assigned to such blocks of code (functions, procedures, subroutines, modules, methods) – so this name can be referred to in place of all the statements

•  Every programming language has its own way for doing these things

Managing complexity

Page 73: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 73

Chunky

Variable – a chunk of data with a name

Method – a chunk of code with a name

The foundations of reuse

Page 74: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 74

Packaging Code

printSquare: ------------------------- ------------------------- ------------------------- -------------------------

•  Refer to printSquare() whenever we want to use the sequence of statements (this is abstraction)

•  Write once, debug once, use many times, update in one place

In Java, we call this a method & declare it inside a class

Page 75: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 75

Methods in Java

•  A method is a named sequence of programming statements

•  To use a method, you call it – but you have to state where the method can be found (i.e. which class the code is inside)

•  You do this by calling the method on an object of the class:

General - objectName.methodName(); Specific - myObject.printSquare();

Static methods are called on a class – no objects needed

Page 76: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 76

Clarification

•  Some programming languages have functions or procedures – Python has functions for e.g.

•  Java has object methods – a bit like a function that an object can perform

terry.forwardMarch();

method object of class turtle

Variable of a class type names an object (e.g. terry)

Page 77: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 77

Code Structure

Source file (ClassName.java)

Class

Method 1

Statement Statement

Method 2

Statement

Page 78: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 78

Classes & Methods

public class ExampleClass{

public void methodOne(){

Statements… }

public void methodTwo(){

Statements… }

}

ExampleClass myObject = new ExampleClass(); myObj.methodOne(); myObj.methodTwo();

A class can declare a number of methods (responsibilities, services, behaviours)

Methods are called on instance objects of the class (dot notation)

Instance object created - one particular ExampleClass

Constructor - a method with same name as class to make an instance object of this class

Page 79: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 79

Classes & Methods - Example

public class SquareClass{

public void printSquare(){ for (int i = 0; i < 5; i++)

System.out.println(“+++++”);

} }

Methods are just a nice way of packaging your code – now just call the method rather than repeat the code

Class name

Method name

Method code in braces

Page 80: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 80

What Do These Mean?

public class SquareClass{

public void printSquare(){ for (int i = 0; i < 5; i++)

System.out.println(“+++++”);

} }

public – can call the method from anywhere in a program (if object is accessible) – a visibility/access modifier

void – method returns no value back to the place of the method call, just does something handy

Page 81: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 81

Written a Method, How Do You Use It?

•  Methods are called on objects – but when you start a program running, you have no objects

•  Remember the main method:

public static void main(String[] args){ }

•  main creates object(s) & calls their methods – the objects then take over the show

•  Only one main method in a program, even if lots of java files

Means method does NOT need to be called on an object

Page 82: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 82

Using Our Example

public class SquareClass{

public void printSquare(){ for (int i = 0; i < 5; i++) System.out.println(“+++++”); }

public static void main(String[] args){ SquareClass myObj = new SquareClass();

myObj.printSquare(); } }

Constructor

Hybrid OO - meaning I am making an instance of a class in the class itself… better to have a separate DRIVER class that does this … but easier for small things for now

Page 83: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 83

Classes, Objects & Methods

(Student.java)

public class Student {

}

public static void main(String[] args) { Student s1 = new Student(); System.out.println(s1.getGpa()): }

public int getgpa() { return this.gpa; }

Other methods here…

Not the best way … Future –> class types & driver classes

public void setGpa(int newGpa) { this.gpa=newGpa; }

private int gpa=0;

Instance variable - gpa - each student object has own value for gpa

Page 84: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 84

Program Flow

•  A method call changes the flow of a program

•  The program jumps & control passes to the method (it may be in an external class/file)

•  Control returns to the point it left when the method has finished

•  With conditionals (branches), loops (repeats) & methods (side-tracks) – we can get quite interesting program flow…

Like being interrupted by a phone call – but you carry on doing what you were previously doing when it is over

Page 85: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 85

Built-in Methods

•  Methods provided by the programming language to carry out routine or complex things: –  System.out.println(“bla”);

•  We know nothing about how built-in methods like println are coded

•  We don’t need to know anything, other than: –  how to use the method (i.e. how to call it

& whether to pass it any arguments - we are passing println a string here)

–  the type of value the method returns println returns nothing - it is void)

Black-box programming

A sort of protocol

Page 86: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 86

How Many Built-in Methods?

•  There are an enormous number of built-in methods to take advantage of (see the API)!

•  However, you are not expected to know about or use all of these – you will find things as & when you need them

They can save you some work!

Page 87: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 87

User-Defined Methods

•  When there is no built-in method to do what you want to do, you have to roll your own…

•  It is exactly like a built-in method, but YOU write the code

•  Your method may do one specific thing, but it is often smarter to make it general purpose

Page 88: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 88

Example

•  We want to write a program to print out this sign

******************************************************* ******************************************************* Welcome ******************************************************* ******************************************************* ******************************************************* *******************************************************

Example from Dr Courtney

Page 89: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 89

A Class & Its Methods - Declaring

public class SignClass{

public void printTwoLines(){ System.out.println(" *******************************"); System.out.println(" *******************************"); }

public void printWelcome(){ System.out.println(" Welcome"); }

public void printFourLines(){ for(int i=1; i <=4; i++) System.out.println("********************************"); }

}

Why use methods?

i is local / temporary variable with restricted scope

Page 90: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 90

Driver Class – Making an Object; Calling its Methods

public class SignDemo{

public static void main(String[] args){ SignClass welcomeSign = new SignClass();

//instantiating an object

welcomeSign.printTwoLines(); //invocation of method in object’s class definition

welcomeSign.printWelcome(); //invocation of method

welcomeSign.printFourLines(); //invocation of method }

} Why do this?

Page 91: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 91

Try it!

•  Go back 2 slides… make a SignClass class exactly as shown

•  Go back 1 slide… make a SignDemo class exactly as shown

•  2 java files in the same source folder - compile and run… see what happens

•  Then, look at the code changes to these 2 classes in the following slides, make the changes and keep re-running your code

Page 92: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 92

Making Methods More General (i)

public void printLines(int number){ for(int i=1; i <=number; i++) System.out.println("*********************"); }

public class SignDemo{ public static void main (String[] args){ SignClass welcomeSign = new SignClass(); welcomeSign.printLines(2); welcomeSign.printWelcome(); welcomeSign.printLines(4); } } Values for parameters to pass into methods

should agree in type, quantity, and position

Create the above method in the SignClass

Parameter

Page 93: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 93

Aside

•  This is called the method SIGNATURE or method declaration

public void printLines(int number)

Visibility/access modifier

The return type

Method name Parameter - variable name and its type

Page 94: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 94

Making Methods More General (ii)

public class SignDemo{

public static void main(String[] args){ SignClass forSaleSign = new SignClass(); forSaleSign.printLines(2);

forSaleSign.decideOnMessage(); forSaleSign.printMessage();

forSaleSign.printLines(4); } }

Need to declare some instance data for the SignClass, so each actual sign object we make can store its own unique message

Page 95: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 95

Making Methods More General (iii)

public class SignClass{ private String message=“”; public void printLines(int number){ for (int i=1; i<=number; i++) System.out.println(" ******************"); }

public void printMessage(){ System.out.println(" " + message"); }

public void decideOnMessage(){ System.out.println(“What message do you want?"); message = scan.nextLine(); } } Make your Scanner object the usual way

Page 96: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 96

Making a General Purpose Method

•  Try the next example too…

Page 97: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 97

Returning to our Example

public class SquareClass{

public void printSquare(){ for (int i = 0; i < 5; i++) System.out.println(“+++++”); }

public static void main(String[] args){ SquareClass myObj = new SquareClass();

myObj.printSquare(); } } Change the method to print a square of ANY size

Constructor

Hybrid OO

Page 98: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 98

Squares of Any Size?

public void printSquare(int side){ for (int row = 0; row < side; row++){

for (int col = 0; col < side; col++){

System.out.print(“+”); }

System.out.println(“\n”);

} }

Parameter to method

To call: myObj.printSquare(8);

Argument to method initialises side (the parameter variable)

Parameter variable

New line character

Varied behaviour – a better abstraction

Scope of side?

Revisiting a few concepts here…

Change the method to print a rectangle of ANY size

Page 99: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 99

Rectangles of Any Size?

public void printRect(int rows, int cols){ for (int row = 0; row < rows; row++){ for (int col = 0; col < cols; col++){ System.out.print(“+”); } System.out.println(“\n”); } }

2 parameters to method

To call: myObj.printRect(2, 4);

An even better abstraction

2 arguments to method – types MUST match, so order is important

Change the method to print a rectangle of ANY size using any character!

Page 100: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 100

Rectangles Using Any Character?

public void printRect(int rows, int cols, char ch){ for (int row = 0; row < rows; row++){ for (int col = 0; col < cols; col++){ System.out.print(ch); } System.out.println(“\n”); } }

3 parameters to method

To call: myObj.printRect(2, 4, ‘*’);

Better abstraction yet!

3 arguments to method – types MUST match, so order is important

Page 101: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 101

Methods That Return Values

•  Does a calculation & returns a value – you must do something with this return value!

public int square(int number){

number = number * number;

return number;

}

Type of the return value declared Parameter is number to square, with its type declared

return statement returns a value & ends the method – MUST be present if method declaration/signature returns a type

To call & use: int x = myObj.square(3);

void methods return no value

Page 102: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 102

The return Statement in Java

•  Returns a value & ends a method – jumps back to where the method was called & inserts its value

•  Methods only return 1 value, but this could be a collection!

public int square(int number){

return number * number;

statement;

}

NEVER executed

Note, constructors have no return type, not even void!

Page 103: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 103

What’s the Difference?

•  Arguments & parameters: two sides of the same coin -- it is just terminology (often used interchangeably)

•  You specify a method signature using parameters

•  You call a method using arguments (i.e. you give actual values for the parameters)

•  When a method is called, arguments are passed into (substituted for) the parameters

Be careful of scope - where do these variables exist?

Page 104: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 104

Parameters / Arguments

•  Special kind of variable used to pass data to a method •  2 ways… •  Pass by reference:

–  parameter variable in the method refers to the same location in memory as the original variable in the method call

–  change the parameter variable, you change the original variable

•  Pass by value: –  method makes a temporary copy of the data in the

original variable –  if you change the parameter variable it has NO

effect on the original variable

Placeholder!

Scope, access, lifetime

Page 105: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 105

More Terminology

•  Encapsulation – taking some code statements, turning them into a method, then using them as a whole: –  simpler to refer to & remember as a whole –  can be used many times, in many places (reuse) –  other people can use your code & you can use

other people’s (a clear contract of use)

•  Generalisation – writing methods that can do more than one particular thing: –  a method that can find the factorial of any number

is more useful than a method that only finds 5!

Page 106: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 106

Recap

•  Methods in Java: –  parameters specify the type & number of variables used by a

method (can have any number) – sometimes called “formal parameters”

–  arguments are the actual values of these variables & they are passed to the method when it is called – sometimes called “actual parameters”

–  scope determines the lifetime of a variable (often delimited by the braces of compound statements & sometimes nested)

–  local / temporary variables are variables declared in a method, & have restricted scope – created when scope entered, destroyed when scope exited (names can be reused if scopes disjoint)

–  if your method specifies a non-void return type, it needs a return statement

Good to make methods as general-purpose & reusable as possible

Page 107: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 107

Writing Java Programs Using Methods

•  No longer a long sequential list of statements

•  Instead, loosely coupled methods that call each other

•  Create small cohesive methods that do a single thing: –  if it does many things, split into multiple methods –  if it is long, split into multiple methods

•  Parameterise your methods to make them general-purpose

Page 108: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 108

Methods in Java

•  A method is a named sequence of programming statements

•  To use a method, you call it – but you have to state where the method can be found (i.e. which class the code is inside)

•  You do this by calling the method on an object of the class:

General - objectName.methodName(); Specific - obj.printSquare();

Methods are called for an object

Page 109: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 109

Writing Java Programs Using Methods

•  No longer a long sequential list of statements

•  Instead, loosely coupled methods that call each other

•  Create small cohesive methods that do a single thing: –  if it does many things, split into multiple methods –  if it is long, split into multiple methods

•  Parameterise your methods to make them general-purpose

What is too long or too much?

Page 110: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 110

Example

•  Assume we will use a single class – what would be a good way of splitting up the work involved in getting a sequence of 100 integers from a user & printing them out in ascending order (i.e. what methods would you write)?

•  3 methods maybe? –  Do the input thing –  Do the sorting thing –  Do the output thing

Method design – try this at home

Logical problem decomposition

Page 111: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 111

Example Continued…

public class Sorter{

public static void main(String[] args){

Sorter myObj = new Sorter();

myObj.inputInt(); myObj.sortInt();

myObj.outputInt();

} }

Declare the 3 methods in the same class here – FOR NOW…

Constructor (a special method)

Lazy OO

Page 112: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 112

Writing the Methods (i)

inputInt():

•  Need to input 100 integers, so need a loop

•  Need a suitable data structure to store them in (use an array)

•  Method will need to return an integer array

Page 113: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 113

Code

public int[] inputInt(){

int[] myInts = new int[100];

// loop to read in integers return myInts;

}

A better method would be flexible & allow the user to say how many integers they want to input

Page 114: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 114

Writing the Methods (ii)

sortInt():

•  Need to take an integer array as an argument

•  Need to sort the array (later)

•  Method will need to return a sorted integer array

Page 115: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 115

Code

public int[] sortInt(int[] myInts){

// sort integers

return myInts; }

Page 116: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 116

Writing the Methods (iii)

outputInt():

•  Need to take an integer array as an argument

•  Need to print out the array elements, so will need a loop

•  Method needs to return nothing, so is void

Page 117: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 117

Code

public void outputInt(int[] myInts){

// loop to print out integers

}

Page 118: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 118

Changing the main Method

public class Sorter{

public static void main(String[] args){

Sorter myObj = new Sorter(); int[] myInts = myObj.inputInt();

myInts = myObj.sortInt(myInts);

myObj.outputInt(myInts); }

}

Many ways to do this

Page 119: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 119

Instance Variables (aka Attributes or Fields)

•  An instance variable belongs to an object & has class scope (i.e. can be used by any instance methods)

public class Sorter{ private int[] myInts = new int[100];

public static void main(String[] args){ Sorter myObj = new Sorter();

int[] myInts = myObj.inputInt(); myInts = myObj.sortInt(myInts); myObj.outputInt(myInts);

} }

Declare instance variables

Declare methods

Constants: final int MAX = 100;

This now simplifies!

Also called data members

Page 120: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 120

Code Structure - Recap

Source file (ClassName.java)

Class

Method 1

Statement Statement

Method 2

Statement

int x; Data declarations - Make these private

Method declarations - Make these operate on the declared data

Page 121: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 121

public int[] inputInt(){

int[] myInts = new int[100]; // loop to read in integers return myInts; }

public void inputInt(){ // myInts = what is read in } public void sortInt(){ // sort integers } public void outputInt(){ // loop to print out integers }

Much Simpler…

Don’t need – myInts is a variable in class scope, so can access it here

No need to return – it can be void

SAFE?

Page 122: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 122

Interfaces

•  The set of methods an object makes available to others to use

private void inputInt() {…} private void sortInt() {…} private void outputInt() {…}

public void doSorting(){ inputInt(); sortInt(); outputInt(); }

public static void main(String[] args){ Sorter myObj = new Sorter(); myObj.doSorting(); }

Control ordering when methods can be called from outside a class

Page 123: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 123

How Would Other Objects Use This?

•  Contracts – to ensure used correctly & in right order

•  Specify order of method call – but can’t enforce it, so better to wrap things up a bit – make all these public methods private & provide a single public method to control what an object is able to do

•  Private variables – means can be used by methods in the same class

•  Private methods – means can be used by other methods in the same class

Page 124: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 124

Public & Private

•  Use methods to write small cohesive units of code, but try to make a minimum number of methods public (i.e. public interface should be thin)

•  Public methods should act as access methods – providing control over the use of private methods & data

•  Variables can also be declared public or private inside a class – it is good practice to make these private & use methods to set & change their values (i.e. getters & setters – also known as accessors & mutators)

•  Default is public … so be careful!

Protected # ?

Called “visibility modifiers” or “access modifiers”

Page 125: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 125

Constructors

public class Olly {

}

public Olly(int newAge){ age = newAge; }

public int getAge() { return age; }

public static void main(String[] args) { Olly babyOlly = new Olly(); Olly youngOlly = new Olly(21); System.out.println(youngOlly.getAge()): }

private int age = 0;

Default constructor

Overloaded constructor

public Olly(){ age = 0; }

Constructors have no return

Page 126: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 126

Method Overloading

•  To perform the same method on different types of data

•  Same method name with multiple parameter lists (method signature)

•  In Java 5.0, return types can be overloaded too

•  E.g. print(counter); print(“Hello!”); …

Constructors are often overloaded

Page 127: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 127

Key Points

•  Programming gets horribly complex if you don’t organise your code

•  Methods provide a way to structure your programs

•  There are built-in methods

•  More interestingly, you can create your own methods – we call these user-defined

Page 128: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 128

Things to Try

•  Go through the lecture slides again & ask me questions if you have them

•  Try working with the code fragments in these slides and see how you get on

•  Read your book chapters on methods

•  Finish exercise sheet 2

•  Work on LAB1 – get as far as you can … seek help if you need it

Work on Lab 1 individually or in pairs

Page 129: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 129

What You Should ALWAYS Do!

•  If you want to learn to program in an OO way (with Java), you need to read the course text … not just once, but again & again … the weekly sessions can only help steer a course for you through this material

•  You should try all the exercises & as many as the programming projects as humanely possible -- it requires your commitment to practice!

To accompany this week’s class, & if you want to keep up, it would be a good idea to ensure you can master the following exercises: - If you have 3rd edition of text: exercises 4.1-4.18 & programming projects 4.1, 4.2, 4.3 & 4.5 - If you have 4-6th edition of text: exercises 5.23-5.34, 6.2, 6.3, 6.4 & programming projects 4.1, 4.3 & 6.1 I will always look at your work & help you with problems if you come to me during office hours

Page 130: CS121: Computer Programming Icsis.pace.edu/~ogotel/teaching/cs121_week9_spring09_big.pdfHello World in Java (Non-OO) // Another Hello World Program – // HelloAgain.java ... Must

CS121/IS223 Week 9, Slide 130

Coming up Next

•  Lots of practice with designing your own classes

•  Objects & object reference variables - what are these object things anyway? Let’s look underneath…

•  Understanding parameter passing – there is more going on behind the scenes than you may think!