Upload
linda-felt
View
226
Download
0
Tags:
Embed Size (px)
Citation preview
Objects & Methods
Defining Classes
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
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;
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)
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)
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)
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)
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)
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
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!)
Objects (Part 2)
Defining Classes
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
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”
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
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!)
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
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;
}
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 …
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 …
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 …
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 …
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;}
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
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
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
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 …
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
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
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
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
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
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
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
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
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
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
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
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
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.
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.
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.
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 …
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