50
242-210 Programming Fundamentals 2: Classes/3 242-210 F II Objectives explain classes and objects introduce fields, constructors, and methods go through two examples Semester 2, 2012-2013 3. Classes and Objec ts Original Slides by Dr. Andrew Davison

242-210 F II

Embed Size (px)

DESCRIPTION

242-210 F II. Semester 2 , 2012-2013. Objectives explain classes and objects introduce fields, constructors, and methods go through two examples. 3 . Classes and Objects. Original Slides by Dr. Andrew Davison. Topics. 1. What are Classes, Objects? 2. The Contents of a Class - PowerPoint PPT Presentation

Citation preview

Page 1: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 1

242-210 F II

• Objectives– explain classes and objects

• introduce fields, constructors, and methods

– go through two examples

Semester 2, 2012-2013

3. Classes and Objects

Original Slides by Dr. Andrew Davison

Page 2: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 2

Topics1. What are Classes, Objects?

2. The Contents of a Class

3. A Stack Class

4. Creating a Stack Object

5. Understanding a Stack Object

6. A Bad Stack Interface

7. Good vs. Bad Interfaces

8. Creating Two Stack Objects

9. Object Types vs. Primitive Types

10. A Ticket Machine

Page 3: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 3

1. What are Classes, Objects?

• A class is a factory for objects.– e.g. a Car class is a factory for Car objects

• A Car class is not a Car object– e.g. a Car factory is not the Cars it makes

Car objects

Carclass

Page 4: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 4

• A class consists of data (fields) and methods.

• Each object gets a copy of the class's data (fields).

• An object uses the methods stored in the class– the class is a kind of method library for all of its objects

Very Important Slide

Page 5: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 5

A Class Involves at least 2 People

• A class is implemented by one person.

• A class is used by other, different people.

• The implementor wants to make a class that is easy to use.

• A user does not care how a class is implemented. He only wants to know the operations that it can carry out (its interface).

Page 6: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 6

A Class for a Stack

A Stack (of plates)

pushpop

Other operations:is EmptytopOf

• This interface helps the implementor decide on the class's operation/methods.

Page 7: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 7

2. The Contents of a Class

public class ClassName{ Fields // variables used by all methods

Constructor(s) // method(s) that initialize an object Methods (functions)}

3 main partsof a class

Page 8: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 8

Fields

• Fields are the variables (data) used by an object.

• Also known as instance variables.

public class Stack{ private int store[]; private int max_len; private int top;  // all methods can use fields}

private int top;

visibility typevariable name

Page 9: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 9

Constructors

• A constructor is a special method which initializes an object's fields.

• A constructor has the same name as the class.

public Stack(int size){ store = new int[size]; max_len = size-1; top = -1;}

Page 10: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 10

Methods

• Methods are functions very like C/C++ functions/methods.

• The methods that are visible to the user (public) in a class depend on the interface of the thing being implemented– e.g. the stack interface → public methods

that a user can call

Page 11: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 11

3. A Stack Class

// Stack.java// Written by the Stack implementor

public class Stack { private int store[]; // hidden data private int max_len; private int top;

public Stack(int size) // visible method { store = new int[size]; max_len = size-1; top = -1; }

:

continued

Page 12: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 12

public boolean push(int number) { if (top == max_len) return false; top++; store[top] = number; return true; } :

continued

Page 13: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 13

public boolean pop() { if (top == -1) return false; top--; return true; }

public int topOf() { return store[top]; }

public boolean isEmpty() { return (top == -1); }

} // end of Stack.java

Page 14: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 14

Stack Class Diagram

'-' means private'+' mean public

class name

fields

methods

constructor

Page 15: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 15

4. Creating a Stack Object

// TestStack.java// Written by the Stack userimport java.io.*;

public class TestStack { public static void main(String args[]) { Stack stk1 = new Stack(10);

stk1.push(42); stk1.push(17); stk1.pop(); System.out.println(“Top value is “ +

stk1.topOf() ); }}

hello object!!

Page 16: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 16

Compilation and Execution

$ javac Stack.java

$ javac TestStack.java

$ java TestStack Top value is 42

Stack.class is in the same directory as TestStack.class.

Page 17: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 17

Notes

• The user cannot directly access the object's data (fields) because it is private.

• The user can call methods because they are public– the methods are the object's user interface

continued

Page 18: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 18

• Object creation:Stack stk1 = new Stack(10)

has three parts:

Stack stk1 // create a variable name, stk1

= new // create a Stack object

Stack(10) // call the constructor to initialize the object state

Page 19: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 19

Stack Object Diagram

Just after object creation:

The stack object has a copy of the class' fields (data), but uses the methods in the 'class library'.

private meansthe user ofthe objectcannot directlyaccess the fields.. . . .store[]

max_len 9

top -1

stk10 1 2 9

Page 20: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 20

• Meaning of a method call:– stk1.push(17) means call the push() method

stored in the Stack class, but apply it to the stk1 object

• Methods work on an object's fields even though the methods are stored in the class.

Page 21: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 21

Stack Object Diagram (later)

42 . . . .store[]

max_len 9

top 1

17

stk1

Just before the call to pop():

Page 22: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 22

5. Understanding a Stack Object

• What does the user need to understand in What does the user need to understand in order to use a Stack object?order to use a Stack object?

• He only needs to understand the interfaceHe only needs to understand the interface– e.g.e.g.

17

42

pushpop

continued

is EmptytopOf

Page 23: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 23

• The user does not need to know how things The user does not need to know how things are implementedare implemented– the user is happy since the interface is simplethe user is happy since the interface is simple

– the implementor is happy since he can change the implementor is happy since he can change the implementation (e.g. make it faster), and the the implementation (e.g. make it faster), and the user will not complain (so long as the interface user will not complain (so long as the interface does not change)does not change)

Page 24: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 24

6. A Bad Stack Interface

// BadStack.java// Written by the ฺBadStack implementor

public class BadStack { private int store[]; private int max_len; public int top;

// constructor and methods same as in Stack:

Page 25: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 25

Creating a BadStack Object// TestBadStack.java// Written by the BadStack userimport java.io.*;

public class TestBadStack { public static void main(String args[]) { BadStack stk1 = new BadStack(10);

stk1.push(42); stk1.push(17); stk1.top = 0; stk1.pop(); System.out.println(“Top value is “ +

stk1.topOf() ); }}

hello object!!

?

Page 26: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 26

Understanding the BadStack Object

• What does the user need to understand in What does the user need to understand in order to use the BadStack object?order to use the BadStack object?

• He needs to understand the interface He needs to understand the interface andand implementationimplementation– e.g.e.g.

17

42

pushpop

+ store[], top, max_len

Page 27: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 27

7. Good vs Bad Interfaces

• A good interface hides the class's implementation– all fields are private

• A good interface can be visualized by the user (e.g the stack diagram)

• A good interface has easy-to-understand public methods.

Page 28: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 28

Kinds of Methods in an Interface

• Aside from the constructor, most public methods can be grouped into two types:– accessor (get) methods

• they return information to the user

• e.g. in Stack: isEmpty(), topOf()

– mutator (set) methods• they change the object's state (its fields)• e.g. in Stack: push(), pop()

Page 29: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 29

An Accessor (Get) Method

public int topOf(){ return store[top];}

return type method name

parameter list (usually empty)

start and end of method body (block)

return statement

visibility modifier

Page 30: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 30

A Mutator (Set) Method

public boolean push(int number) { if (top == max_len) return false; top++; store[top] = number; return true; }

return typemethod name parameter(s

)

visibility modifier

fields being mutated

Page 31: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 31

• Many objects can be created from a class::

// in main() of TestStackStack stk1 = new Stack(10);Stack stk2 = new Stack(20);stk1.push(27);stk1.push(13);stk2.push(10);el = stk2.topOf();

:

create twoobjects

8. Creating Two Stack Objects

Page 32: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 32

Stack Objects Diagrams

27 . . . .store[]

max_len 8

top 1

13stk1

10 . . . .store[]

max_len 19

top 0

stk2

Just before the call to topOf():

Page 33: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 33

Notes

• The two objects have two copies of the class's data– changes in one object do not affect the other

object

• Both objects use the methods in the class– stk1.push(13) means call push() and apply

it to the data inside stk1

Page 34: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 34

9. Object Types vs. Primitive Types

32

object type

primitive type

Foo a = new Foo();

int i;i = 32;

a Foo object

i

Primitive types include: int, float, double, char, byte

Page 35: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 35

Assignment Differences

32

Foo a = new Foo();Foo b;b = a;

int a = 32;int b;b = a;

b

32

a

ba

Foo object

copy the link (the reference)

copy the value

Page 36: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 36

10. A Ticket Machine

insert moneyprintticket

show price(and other info)

show balance(the amount

of money entered)

• The required interface helps the implementor decide on the class’s methods.

give change

Page 37: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 37

10.1. Class Diagram

accessormethods

mutator method

constructor

accessor/mutator methods(tricky tounderstand)

Page 38: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 38

10.2 Ticket Machine Class

public class TicketMachine{ private int price; // price of a ticket private int balance; // amount entered by customer private int total; // total money in machine

public TicketMachine(int ticketCost) { price = ticketCost; // set the ticket price balance = 0; total = 0; }

continued

Page 39: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 39

public int getPrice()

{ return price; }

public int getBalance()

{ return balance; }

public int getTotal()

{ return total; }

continued

Page 40: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 40

public void insertMoney(int amount) // process money inserted into the machine { if (amount > 0) balance = balance + amount; else System.out.println("Use a positive amount: "

+ amount); }

continued

Page 41: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 41

public void printTicket() { if (balance >= price) {// if enough money inserted // Simulate the printing of a ticket. System.out.println("##################"); System.out.println("# Ticket"); System.out.println("# " + price + " baht."); System.out.println("##################"); System.out.println();

// Update the total collected with the price. total = total + price; // Reduce the balance by the prince. balance = balance - price; } else // report error System.out.println( "You must insert at least: " +

(price - balance) + " more baht."); } // end of printTicket()

continued

Page 42: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 42

public int refundBalance() { int amountToRefund; amountToRefund = balance; balance = 0; //clear ticket machine's balance return amountToRefund; //return balance amount }

} // end of TicketMachine class

Page 43: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 43

10.3. Local Variables

• Fields are one sort of variable– they store values through the life of an object– they are accessible by all the methods

• Methods can include shorter-lived variables:– they exist only as long as the method is being executed– they are only accessible from within the method

Page 44: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 44

Local Variable Example

public int refundBalance(){ int amountToRefund; amountToRefund = balance; balance = 0; return amountToRefund;}

A local variable

No visibilitymodifier

Page 45: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 45

10.4. Using a TicketMachine Object

public class TMDemo{ public static void main(String[] args) { TicketMachine tm = new TicketMachine(10);

// tickets cost 10

System.out.println("Ticket price: " + tm.getPrice());

System.out.println("Current total: " + tm.getTotal());

System.out.println("Insert 5 baht"); tm.insertMoney(5);

:

Page 46: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 46

System.out.println("Insert 10 baht"); tm.insertMoney(10);

System.out.println("Current balance: " + tm.getBalance());

tm.printTicket(); System.out.println("Current balance: " +

tm.getBalance()); System.out.println("Current total: " +

tm.getTotal());

:

Page 47: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 47

System.out.println("Request Change"); System.out.println("Change is: " +

tm.refundBalance());

System.out.println("Current balance: " + tm.getBalance());

} // end of main()

} // end of TMDemo class

Page 48: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 48

Compilation

$ javac TicketMachine.java

$ javac TMDemo.java

TicketMachine.class is in the same directory as TMDemo.class.

Page 49: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 49

Output of java TMDemoTicket price: 10Current total: 0Insert 5 bahtInsert 10 bahtCurrent balance: 15################### Ticket# 10 baht.##################

Current balance: 5Current total: 10Request ChangeChange is: 5Current balance: 0

Page 50: 242-210 F II

242-210 Programming Fundamentals 2: Classes/3 50

TicketMachine Object Diagram

price 10

balance 0

tm

Just after object creation:

The TicketMachine object has a copy of the class' data, but uses the methods in the 'class library'.

total 0