Title: Objects
1Objects Methods
2Reference 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
3Reference Variables Revisited
- Think of Objects as balloons!
- references are like strings (aka handles)
- Idea from Beginning Java Objects by Jacquie
Barker (Wrox)
BankAccount x, y, z x new BankAccount() y
x z new BankAccount() y z x z
x
y
z
(null)
(null)
(null)
4Reference Variables Revisited
- Think of Objects as balloons!
- references are like strings (aka handles)
- Idea from Beginning Java Objects by Jacquie
Barker (Wrox)
BankAccount x, y, z x new BankAccount() y
x z new BankAccount() y z x z
x
y
z
(null)
(null)
5Reference Variables Revisited
- Think of Objects as balloons!
- references are like strings (aka handles)
- Idea from Beginning Java Objects by Jacquie
Barker (Wrox)
BankAccount x, y, z x new BankAccount() y
x z new BankAccount() y z x z
x
y
z
(null)
6Reference Variables Revisited
- Think of Objects as balloons!
- references are like strings (aka handles)
- Idea from Beginning Java Objects by Jacquie
Barker (Wrox)
BankAccount x, y, z x new BankAccount() y
x z new BankAccount() y z x z
x
y
z
7Reference Variables Revisited
- Think of Objects as balloons!
- references are like strings (aka handles)
- Idea from Beginning Java Objects by Jacquie
Barker (Wrox)
BankAccount x, y, z x new BankAccount() y
x z new BankAccount() y z x z
x
y
z
8Reference Variables Revisited
- Think of Objects as balloons!
- references are like strings (aka handles)
- Idea from Beginning Java Objects by Jacquie
Barker (Wrox)
BankAccount x, y, z x new BankAccount() y
x z new BankAccount() y z x z
x
y
z
9Reference Variables Revisited
- Think of Objects as balloons!
- references are like strings (aka handles)
- Idea from Beginning Java Objects by Jacquie
Barker (Wrox)
BankAccount x, y, z x new BankAccount() y
x z new BankAccount() y z x z
x
y
z
10Something to think about
- Suppose
- int 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. (Its a joint account!)
11Objects (Part 2)
12Using BankAccount objects
BankAccount aliceAccount new BankAccount() Bank
Account 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 instances own balance
- aliceAccount.deposit( 250 ) changes only
aliceAccounts balance, not bobAccounts
13Classes
- 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 objects own balance field - A Class is like a recipe or template
14Defining Classes
- public class BankAccount
-
- private int balance // current amount
- public BankAccount()
-
- // does nothing. defaults to balance0
-
-
- public int getBalance()
-
- return balance
-
-
- public void deposit( int amount )
-
15Applets 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()
16Method Declaration
public void deposit ( int
amount ) balance amount
17Value-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 ltexpressiongt
18How Methods Work
BankApplet.java
int aliceBalance aliceAccount.getBalance()
State of Memory
When the line above is run
aliceBalance
- Find object pointed to by aliceAccount
- Find code for class of that object
- Find code for getBalance()
- Run code
- Return value
- Use returned value
aliceAccount
BankAccount
int balance
100
19How Methods Work
BankApplet.java
int aliceBalance aliceAccount.getBalance()
State of Memory
When the line above is run
aliceBalance
- Find object pointed to by aliceAccount
- Find code for class of that object
- Find code for getBalance()
- Run code
- Return value
- Use returned value
aliceAccount
BankAccount
int balance
100
20How Methods Work
BankApplet.java
int aliceBalance aliceAccount.getBalance()
State of Memory
When the line above is run
aliceBalance
- Find object pointed to by aliceAccount
- Find code for class of that object
- Find code for getBalance()
- Run code
- Return value
- Use returned value
aliceAccount
BankAccount
int balance
100
21How Methods Work
BankApplet.java
int aliceBalance aliceAccount.getBalance()
State of Memory
When the line above is run
aliceBalance
- Find object pointed to by aliceAccount
- Find code for class of that object
- Find code for getBalance()
- Run code
- Return value
- Use returned value
aliceAccount
BankAccount
int balance
100
22How Methods Work
BankApplet.java
public int getBalance() return balance
int aliceBalance aliceAccount.getBalance()
State of Memory
When the line above is run
aliceBalance
- Find object pointed to by aliceAccount
- Find code for class of that object
- Find code for getBalance()
- Run code
- Return value
- Use returned value
aliceAccount
BankAccount
int balance
100
23How Methods Work
BankAccount.java
BankApplet.java
public int getBalance() return balance
int aliceBalance aliceAccount.getBalance()
State of Memory
When the line above is run
aliceBalance
- Find object pointed to by aliceAccount
- Find code for class of that object
- Find code for getBalance()
- Run code
- Return value
- Use returned value
aliceAccount
BankAccount
int balance
100
24How Methods Work
BankAccount.java
BankApplet.java
public int getBalance() return balance
int aliceBalance aliceAccount.getBalance()
State of Memory
When the line above is run
aliceBalance
- Find object pointed to by aliceAccount
- Find code for class of that object
- Find code for getBalance()
- Run code
- Return value
- Use returned value
100
aliceAccount
BankAccount
int balance
100
25Three Kinds of Variables
- Field (aka Attribute or Instance Variable)
- Variables declared inside a class code, but
outside any methods - Part of objects permanent state
- Use for state that is retained between method
calls - Local Variable
- Variables declared inside a method definition
- Only exists while were 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
26Sample Method
From Wus CurrencyConverter class
public double fromDollar( double dollar
) double amount, fee fee
exchangeRate - feeRate amount dollar
fee return amount
27Local Variables Example
Code
public double fromDollar( double dollar )
double amount, fee fee exchangeRate -
feeRate amount dollar fee return
amount
amt yenConverter.fromDollar( 200 )
A. fromDollars local variables (amount and fee)
do not exist before the method call
amt
State of Memory
28Local Variables Example
Code
public double fromDollar( double dollar )
double amount, fee fee exchangeRate -
feeRate amount dollar fee return
amount
B
amt yenConverter.fromDollar( 200 )
B. Memory space is allocated for the local
variables and parameter.Parameters value is
copied from the argument.
State of Memory
29Local Variables Example
Code
public double fromDollar( double dollar )
double amount, fee fee exchangeRate -
feeRate amount dollar fee return
amount
amt yenConverter.fromDollar( 200 )
C
C. Computed values are assigned to the local
variables.
amt
dollar
24846.3
124.2315
State of Memory
30Local Variables Example
Code
public double fromDollar( double dollar )
double amount, fee fee exchangeRate -
feeRate amount dollar fee return
amount
amt yenConverter.fromDollar( 200 )
D
D. Memory space for local variables and
parameters is deallocated upon exiting the
fromDollar method.
amt
24846.3
State of Memory
31Three Kinds of Variables
- Field (aka Attribute or Instance Variable)
- Variables declared inside a class code, but
outside any methods - Part of objects permanent state
- Use for state that is retained between method
calls - Local Variable
- Variables declared inside a method definition
- Only exists while were 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
32Passing 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
33Pass-By-Value Scheme
Code
A
x 10 y 20 tester.myMethod( x, y )
public void myMethod( int one, float two )
one 25 two 35.4f
A. Local variables do not exist before the
method execution
State of Memory
34Pass-By-Value Scheme
Code
x 10 y 20 tester.myMethod( x, y )
public void myMethod( int one, float two )
one 25 two 35.4f
B
B. The values of arguments are copied to the
parameters.
State of Memory
35Pass-By-Value Scheme
Code
x 10 y 20 tester.myMethod( x, y )
public void myMethod( int one, float two )
one 25 two 35.4f
C. The values of parameters are changed.
State of Memory
36Pass-By-Value Scheme
Code
x 10 y 20 tester.myMethod( x, y )
public void myMethod( int one, float two )
one 25 two 35.4f
D
D. Parameters are erased. Arguments remain
unchanged.
State of Memory
37Constructors
- 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
38Defining Constructors
- A constructor will have the following form
- public ltclass namegt ( ltparametersgt
) ltstatementsgt -
Currently, BankAccounts constructor has no
arguments and does nothing.
public BankAccount ( )
39Multiple 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
These constructors will not conflict with each
other, and therefore, valid.
40A 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.
41The 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. (Well discuss another way later.)
Dont forget to set the field through an
assignment statement.
42Access 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)
43Keeping 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 dont even have to know that logging is
taking place