43
Objects & Methods Defining Classes

Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by

Embed Size (px)

Citation preview

Page 1: Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by

Objects & Methods

Defining Classes

Page 2: Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by

Slide 2

Reference Variables Revisited

Remember: Object variables are references (aka pointers) Point to “null” by default Need to call new to create

a new object Different variables can point to same

object at the same time

Page 3: Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by

Slide 3

Reference Variables Revisited

Think of Objects as balloons! references are like strings (aka “handles”) Idea from “Beginning Java Objects” by Jacquie

Barker (Wrox)

x y z(null) (null) (null)

BankAccount x, y, z;

x = new BankAccount();

y = x;

z = new BankAccount();

y = z;

x = z;

Page 4: Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by

Slide 4

Reference Variables Revisited

x y z(null) (null)

BankAccount x, y, z;

x = new BankAccount();

y = x;

z = new BankAccount();

y = z;

x = z;

Think of Objects as balloons! references are like strings (aka “handles”) Idea from “Beginning Java Objects” by Jacquie

Barker (Wrox)

Page 5: Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by

Slide 5

Reference Variables Revisited

x y z(null)

BankAccount x, y, z;

x = new BankAccount();

y = x;

z = new BankAccount();

y = z;

x = z;

Think of Objects as balloons! references are like strings (aka “handles”) Idea from “Beginning Java Objects” by Jacquie

Barker (Wrox)

Page 6: Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by

Slide 6

Reference Variables Revisited

x y z

BankAccount x, y, z;

x = new BankAccount();

y = x;

z = new BankAccount();

y = z;

x = z;

Think of Objects as balloons! references are like strings (aka “handles”) Idea from “Beginning Java Objects” by Jacquie

Barker (Wrox)

Page 7: Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by

Slide 7

Reference Variables Revisited

BankAccount x, y, z;

x = new BankAccount();

y = x;

z = new BankAccount();

y = z;

x = z;

x y z

Think of Objects as balloons! references are like strings (aka “handles”) Idea from “Beginning Java Objects” by Jacquie

Barker (Wrox)

Page 8: Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by

Slide 8

Reference Variables Revisited

BankAccount x, y, z;

x = new BankAccount();

y = x;

z = new BankAccount();

y = z;

x = z;

x y z

Think of Objects as balloons! references are like strings (aka “handles”) Idea from “Beginning Java Objects” by Jacquie

Barker (Wrox)

Page 9: Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by

Slide 9

Think of Objects as balloons! references are like strings (aka “handles”) Idea from “Beginning Java Objects” by Jacquie

Barker (Wrox)

Reference Variables Revisited

BankAccount x, y, z;

x = new BankAccount();

y = x;

z = new BankAccount();

y = z;

x = z;

x y z

Page 10: Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by

Slide 10

Something to think about

Supposeint a;

a = 150000;

int b = a;

a = a + 300000;

int c = b;

BankAccount x = new BankAccount();

x.deposit( 150000 );

BankAccount y = x;

x.deposit( 300000 );

int z = y.getBalance();

What is the final value of c? z? Why? Answer: c is 150000,

while z is 450000 Why? Because a

primitive-type variable copies the actual value, while object-type variables copies the reference

b is independent from a

on the other hand, y and x refer to the same BankAccount instance. (It’s a joint account!)

Page 11: Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by

Objects (Part 2)

Defining Classes

Page 12: Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by

Slide 12

Using BankAccount objects

BankAccount aliceAccount = new BankAccount();BankAccount bobAccount = new BankAccount(); BankAccount chuckAccount = new BankAccount();

aliceAccount.deposit( 250 );bobAccount.deposit( 100 );int x = chuckAccount.getBalance();

Note: all BankAccount instances have the same structure

int balance field int getBalance(), deposit(int), and withdraw(int) methods

But each BankAccount instance has a distinct identity

each instance has its own values for fields (e.g., balance) methods work on an instance’s own balance

aliceAccount.deposit( 250 ) changes only aliceAccount’s balance, not bobAccount’s

Page 13: Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by

Slide 13

Classes

A Class describes the general structure of objects belonging to that class fields/attributes (state) methods (behavior)

e.g., The BankAccount class says that: all BankAccount objects have its own balance

field of type int all BankAccount objects have a deposit method

which increments the object’s own balance field A Class is like a “recipe” or “template”

Page 14: Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by

Slide 14

Defining Classes

public class BankAccount {

private int balance; // current amount

public BankAccount() { // does nothing. defaults to balance=0 }

public int getBalance() { return balance; } public void deposit( int amount ) { balance += amount; }}

Class name(must be same as file name)

Fields

Constructors

Methods

Page 15: Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by

Slide 15

Methods

Applets are Objects too!

public class BankApplet1 extends IOApplet { BankAccount account; public void setup() { account = new BankAccount(); addInput( "Amount" ); addButton( "Deposit" ); addOutput(); println( "Balance is P" + account.getBalance() + "." ); } public void onButtonPressed() { int amount = getInt( "Amount" ); account.deposit( amount ); clearOutput(); println( "Balance is P" + account.getBalance() + "." ); }}

Class name

Fields(data members)

extends BankApplet1 “is a” IOApplet, and “inherits” code from it. (More later!)

Page 16: Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by

Slide 16

Method Declaration<modifier> <return type> <method name> ( <parameters> )

{

<statements>

}

public void deposit ( int amount )

{

balance += amount;

}

StatementsStatements

ModifierModifier Return TypeReturn Type Method NameMethod Name ParameterParameter

Page 17: Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by

Slide 17

Value-Returning Method We call a method that returns a value a

value-returning method , or non-void method. A value-returning method must include a

return statement in the following format:return <expression> ;

public int getBalance( )

{

return balance;

}

Page 18: Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by

Slide 18

How Methods WorkBankApplet.java

State of Memory

…int aliceBalance = aliceAccount.getBalance(); …

aliceAccount

BankAccount

aliceBalance

100int balance

1) Find object pointed to by aliceAccount

2) Find code for class of that object

3) Find code for getBalance() 4) Run code5) Return value6) Use returned value

When the line above is run …

Page 19: Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by

Slide 19

How Methods WorkBankApplet.java

State of Memory

…int aliceBalance = aliceAccount.getBalance(); …

aliceAccount

getBalance()

BankAccount

aliceBalance

100int balance

1) Find object pointed to by aliceAccount

2) Find code for class of that object

3) Find code for getBalance() 4) Run code5) Return value6) Use returned value

When the line above is run …

Page 20: Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by

Slide 20

How Methods WorkBankApplet.java

State of Memory

…int aliceBalance = aliceAccount.getBalance(); …

public class BankAccount { private int balance; // current amount public BankAccount() { // does nothing. defaults to balance=0 } public int getBalance() { return balance; } public void deposit( int amount ) { balance += amount; }}

BankAccount.java

aliceAccount

getBalance()

BankAccount

aliceBalance

100int balance

1) Find object pointed to by aliceAccount

2) Find code for class of that object

3) Find code for getBalance() 4) Run code5) Return value6) Use returned value

When the line above is run …

Page 21: Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by

Slide 21

How Methods WorkBankApplet.java

State of Memory

…int aliceBalance = aliceAccount.getBalance(); …

public class BankAccount { private int balance; // current amount public BankAccount() { // does nothing. defaults to balance=0 } public int getBalance() { return balance; } public void deposit( int amount ) { balance += amount; }}

BankAccount.java

aliceAccount

getBalance()

BankAccount

aliceBalance

100int balance

1) Find object pointed to by aliceAccount

2) Find code for class of that object

3) Find code for getBalance()

4) Run code5) Return value6) Use returned value

When the line above is run …

Page 22: Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by

Slide 22

How Methods WorkBankApplet.java

State of Memory

…int aliceBalance = aliceAccount.getBalance(); …

aliceAccount

getBalance()

BankAccount

aliceBalance

100int balance

1) Find object pointed to by aliceAccount

2) Find code for class of that object

3) Find code for getBalance() 4) Run code5) Return value6) Use returned value

When the line above is run …

public class BankAccount { private int balance; // current amount public BankAccount() { // does nothing. defaults to balance=0 } public int getBalance() { return balance; } public void deposit( int amount ) { balance += amount; }}

BankAccount.java

public int getBalance(){ return balance;}

Page 23: Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by

Slide 23

How Methods WorkBankApplet.java

State of Memory

…int aliceBalance = aliceAccount.getBalance(); …

public int getBalance(){ return balance;}

BankAccount.java

aliceAccount

getBalance()

BankAccount

aliceBalance

100int balance

1) Find object pointed to by aliceAccount

2) Find code for class of that object

3) Find code for getBalance() 4) Run code5) Return value6) Use returned value

When the line above is run …

100

Page 24: Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by

Slide 24

How Methods WorkBankApplet.java

State of Memory

…int aliceBalance = aliceAccount.getBalance(); …

public int getBalance(){ return balance;}

BankAccount.java

aliceAccount

getBalance()

BankAccount

aliceBalance

100int balance

1) Find object pointed to by aliceAccount

2) Find code for class of that object

3) Find code for getBalance() 4) Run code5) Return value6) Use returned value

When the line above is run …

100

100

Page 25: Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by

Slide 25

Three Kinds of Variables

Field (aka Attribute or Instance Variable) Variables declared inside a class’ code, but outside any

methods Part of object’s “permanent” state Use for state that is retained between method calls

Local Variable Variables declared inside a method definition Only exists while we’re inside the method Use as a “scratchpad” (temporary storage) during a

computation Parameter

Variables declared in the parentheses of a method definition Holds a copy of the value or reference passed as an argument

to the method call Is also a local variable – i.e., only exists inside the method

Page 26: Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by

Slide 26

Sample Method

public double fromDollar( double dollar )

{

double amount, fee;

fee = exchangeRate - feeRate;

amount = dollar * fee;

return amount;

}

ParameterParameter

Local Variables

Local Variables

Fields *Fields *

* Although not shown here, exchangeRate and feeRate were declaredinside the CurrencyConverter class, but outside any methods

From Wu’s CurrencyConverter class …

Page 27: Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by

Slide 27

Local Variables ExampleCode

State of Memory

amt = yenConverter.fromDollar( 200 );

public double fromDollar( double dollar ){ double amount, fee;

fee = exchangeRate - feeRate; amount = dollar * fee;

return amount;}

AA

A. A. fromDollar’s local variables (amount and fee) do not exist before the method call

A. A. fromDollar’s local variables (amount and fee) do not exist before the method call

At before fromDollarAA

CurrencyConverter

129.2315exchangeRate

5.0feeRate

yenConverteramt 0.0

Page 28: Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by

Slide 28

Local Variables ExampleCodeamt = yenConverter.fromDollar( 200 );

public double fromDollar( double dollar ){ double amount, fee;

fee = exchangeRate - feeRate; amount = dollar * fee;

return amount;}

BB

B. B. Memory space is allocated for the local variables and parameter.

Parameter’s value is copied from the argument.

B. B. Memory space is allocated for the local variables and parameter.

Parameter’s value is copied from the argument.

After is executedBB

dollar 200.0

amount

fee

State of Memory

CurrencyConverter

129.2315exchangeRate

5.0feeRate

yenConverteramt 0.0

Page 29: Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by

Slide 29

amount

fee

Local Variables ExampleCodeamt = yenConverter.fromDollar( 200 );

public double fromDollar( double dollar ){ double amount, fee;

fee = exchangeRate - feeRate; amount = dollar * fee;

return amount;}

CC

C. C. Computed values are assigned to the local variables.

C. C. Computed values are assigned to the local variables.

After is executedCC

dollar

24846.324846.3

200.0

124.2315124.2315

CurrencyConverter

129.2315exchangeRate

5.0feeRate

yenConverteramt 0.0

State of Memory

Page 30: Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by

Slide 30

amt 24846.3

Local Variables ExampleCodeamt = yenConverter.fromDollar( 200 );

public double fromDollar( double dollar ){ double amount, fee;

fee = exchangeRate - feeRate; amount = dollar * fee;

return amount;}

DD

D. D. Memory space for local variables and parameters is deallocated upon exiting the fromDollar method.

D. D. Memory space for local variables and parameters is deallocated upon exiting the fromDollar method.

At after fromDollarDD

CurrencyConverter

129.2315exchangeRate

5.0feeRate

yenConverter

State of Memory

Page 31: Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by

Slide 31

Three Kinds of Variables

Field (aka Attribute or Instance Variable) Variables declared inside a class’ code, but outside any

methods Part of object’s “permanent” state Use for state that is retained between method calls

Local Variable Variables declared inside a method definition Only exists while we’re inside the method Use as a “scratchpad” (temporary storage) during a

computation Parameter

Variables declared in the parentheses of a method definition Holds a copy of the value or reference passed as an argument

to the method call Is also a local variable – i.e., only exists inside the method

Page 32: Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by

Slide 32

Passing Parameters Arguments are matched to parameters from left to

right. Types must match The number of arguments in the method call must

match the number of parameters in the method definition

Arguments are passed to a method using the pass-by-value scheme

Parameters and arguments do not have to have the same name

Whether or not they have the same name, parameters are separate copies of the arguments

Parameters are local to the method, i.e., they only exist while inside the method. Changes made to the parameters will not affect the value of corresponding arguments

Page 33: Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by

Slide 33

Pass-By-Value Scheme

State of Memory

public void myMethod( int one, float two ){ one = 25; two = 35.4f;}

AA

A. A. Local variables do not exist before the method execution

A. A. Local variables do not exist before the method execution

At before myMethodAA

Codex = 10;y = 20;tester.myMethod( x, y );

xx 1010

y 1020

Page 34: Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by

Slide 34

Pass-By-Value Scheme

State of Memory

B. B. The values of arguments are copied to the parameters.

B. B. The values of arguments are copied to the parameters.

Values are copied at BB

public void myMethod( int one, float two ){ one = 25; two = 35.4f;}

Codex = 10;y = 20;tester.myMethod( x, y ); BB

xx 1010

y 1020

one 1010

two 1020.0f

Page 35: Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by

Slide 35

Pass-By-Value Scheme

CC

State of Memory

C. C. The values of parameters are

changed.

C. C. The values of parameters are

changed.

After is executedCC

public void myMethod( int one, float two ){ one = 25; two = 35.4f;}

Codex = 10;y = 20;tester.myMethod( x, y );

xx 1010

y 1020

one 1025

two 1035.4f

Page 36: Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by

Slide 36

Pass-By-Value SchemeCode

DD

State of Memory

D. D. Parameters are erased. Arguments remain unchanged.

D. D. Parameters are erased. Arguments remain unchanged.

At after myMethodDD

public void myMethod( int one, float two ){ one = 25; two = 35.4f;}

x = 10;y = 20;tester.myMethod( x, y );

xx 1010

y 1020

Page 37: Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by

Slide 37

Constructors

A constructor is a special method that is called with the new command

Used for initializing an object to a valid state Name of a constructor must be the same as

the name of the class No return type If no constructor is defined, the Java

compiler will include a default constructor with no arguments and no body

Page 38: Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by

Slide 38

Defining Constructors A constructor will have the following form:

public <class name> ( <parameters> ){

<statements>

}

public BankAccount ( )

{

}

Currently, BankAccount’s constructor has no arguments and does nothing.

Currently, BankAccount’s constructor has no arguments and does nothing.

StatementsStatements

ModifierModifier Class NameClass Name ParameterParameter

Page 39: Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by

Slide 39

Multiple Constructors A class can include multiple constructors without any problem,

as long as the constructors defined for the class have either A different number of parameters Different data types for the parameters if the number of parameters is

the same This is known as “overloading” and can also be done with

ordinary methods

public MyClass( int value ) { … }

public MyClass( ) { … }

public MyClass( float value ) { … }

public MyClass( String name, float value ) { … }

These constructors will not conflict with each other, and therefore, valid.

These constructors will not conflict with each other, and therefore, valid.

Page 40: Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by

Slide 40

A Common Misconception

public class StudentRecord

{

private String name; // current amount

public StudentRecord( String name )

{

}

… methods (not shown) …

}

Some people think that you can set a field by simply giving the parameter same name as the field. THIS DOES NOT WORK.

The parameter and the field are two different and independent variables, even if they have the same name.

Page 41: Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by

Slide 41

The Correct Way (for now)

public class StudentRecord

{

private String name; // current amount

public StudentRecord( String initialName )

{

name = initialName;

}

… methods (not shown) …

}

Give the parameter a different name in order to be clear. (We’ll discuss another way later.)

Don’t forget to set the field through an assignment statement.

Page 42: Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by

Slide 42

Access Modifiers public and private designate the

accessibility of fields and methods private means code in other classes cannot

access it public means anybody can access it no modifier means public within the same

directory (more later when we get to “packages”)

class Test{ public int memberOne; private int memberTwo;}

Test myTest = new MyTest();

myTest.memberOne = 10;

myTest.memberTwo = 20;

in another class …

Page 43: Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by

Slide 43

Keeping fields private

In general, fields should be private so we can have the flexibility of changing the implementation details of the class

e.g., Suppose we want to keep a log of deposits if balance is public, we cannot guarantee that

deposits will be logged because anyone can increment balance directly

if balance is private, we can simply modify the deposit method

Since users can only increment balance by calling deposit, all deposits will be logged.

Users don’t even have to know that logging is taking place