Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
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) BankAccount x, y, z; x = new BankAccount(); y = x; z = new BankAccount(); y = z; x = z; x (null) y (null) z (null) Slide 4 Reference 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 (null) z (null) Slide 5 Reference 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) Slide 6 Reference 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 Slide 7 Reference 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 Slide 8 Reference 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 Slide 9 Reference 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 Something 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(); Slide 10 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 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 12 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: Slide 13 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; Class name (must be same as file name) // current amount public BankAccount() { // does nothing. defaults to balance=0 } public int getBalance() { return balance; } public void deposit( int amount ) { balance += amount; } } Fields Constructors Methods Applets are Objects too! Class name public class BankApplet1 { BankAccount account; extends IOApplet extends BankApplet1 “is a” IOApplet, and “inherits” code from it. (More later!) Fields public void setup() { (data members) 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() + "." ); } } Slide 15 Methods Slide 16 Method Declaration <modifier> <return type> <method name> ( <parameters> { <statements> } Modifier public Return Type void Method Name deposit Parameter ( int amount { balance += amount; } Statements ) ) Value-Returning Method We call a method that returns a value a valuereturning 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 17 Slide 18 How Methods Work BankApplet.java … int aliceBalance = aliceAccount.getBalance(); … When the line above is run … 1) Find object pointed to by aliceAccount 2) Find code for class of that object 3) Find code for getBalance() 4) Run code 5) Return value 6) Use returned value State of Memory aliceBalance aliceAccount BankAccount int balance 100 Slide 19 How Methods Work BankApplet.java … int aliceBalance = aliceAccount.getBalance(); … When the line above is run … 1) Find object pointed to by aliceAccount 2) Find code for class of that object 3) Find code for getBalance() 4) Run code 5) Return value 6) Use returned value State of Memory aliceBalance aliceAccount BankAccount getBalance() int balance 100 Slide 20 How Methods Work BankApplet.java … int aliceBalance = aliceAccount.getBalance(); … When the line above is run … 1) Find object pointed to by aliceAccount 2) Find code for class of that object 3) Find code for getBalance() 4) Run code 5) Return value 6) Use returned value BankAccount.java 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; } } State of Memory aliceBalance aliceAccount BankAccount getBalance() int balance 100 Slide 21 How Methods Work BankApplet.java … int aliceBalance = aliceAccount.getBalance(); … When the line above is run … 1) Find object pointed to by aliceAccount 2) Find code for class of that object 3) Find code for getBalance() 4) Run code 5) Return value 6) Use returned value BankAccount.java 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; } } State of Memory aliceBalance aliceAccount BankAccount getBalance() int balance 100 Slide 22 How Methods Work BankApplet.java … int aliceBalance = aliceAccount.getBalance(); … When the line above is run … 1) Find object pointed to by aliceAccount 2) Find code for class of that object 3) Find code for getBalance() 4) Run code 5) Return value 6) Use returned value BankAccount.java 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; } } public int getBalance() { return balance; } State of Memory aliceBalance aliceAccount BankAccount getBalance() int balance 100 Slide 23 How Methods Work BankApplet.java … int aliceBalance = aliceAccount.getBalance(); … When the line above is run … 1) Find object pointed to by aliceAccount 2) Find code for class of that object 3) Find code for getBalance() 4) Run code 5) Return value 6) Use returned value BankAccount.java public int getBalance() { return balance; } State of Memory aliceBalance aliceAccount BankAccount getBalance() 100 int balance 100 Slide 24 How Methods Work BankApplet.java … int aliceBalance = aliceAccount.getBalance(); … When the line above is run … 1) Find object pointed to by aliceAccount 2) Find code for class of that object 3) Find code for getBalance() 4) Run code 5) Return value 6) Use returned value BankAccount.java public int getBalance() { return balance; } State of Memory aliceBalance 100 aliceAccount BankAccount getBalance() 100 int balance 100 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 Slide 25 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 From Wu’s CurrencyConverter class … public double fromDollar( double dollar ) { double amount, fee; Parameter Local Variables fee = exchangeRate - feeRate; amount = dollar * fee; return amount; Fields * } * Although not shown here, exchangeRate and feeRate were declared inside the CurrencyConverter class, but outside any methods Local Variables Example Code A amt = yenConverter.fromDollar( 200 ); Slide 27 public double fromDollar( double dollar ) { double amount, fee; fee = exchangeRate - feeRate; amount = dollar * fee; return amount; } At A before fromDollar yenConverter Currency Converter amt 0.0 A. fromDollar’s local variables (amount and fee) do not exist before the method call exchangeRate 129.2315 feeRate 5.0 State of Memory Local Variables Example Code public double fromDollar( double dollar ) { double amount, fee; fee = exchangeRate - feeRate; amount = dollar * fee; return amount; } amt = yenConverter.fromDollar( 200 ); After B yenConverter Currency Converter exchangeRate 129.2315 feeRate 5.0 Slide 28 is executed amt dollar 0.0 200.0 amount fee State of Memory B B. Memory space is allocated for the local variables and parameter. Parameter’s value is copied from the argument. Slide 29 Local Variables Example Code public double fromDollar( double dollar ) { double amount, fee; fee = exchangeRate - feeRate; amount = dollar * fee; return amount; } amt = yenConverter.fromDollar( 200 ); C After C yenConverter Currency Converter exchangeRate 129.2315 feeRate 5.0 is executed amt dollar amount 0.0 C. Computed 200.0 24846.3 124.2315 fee State of Memory values are assigned to the local variables. Local Variables Example Code amt = yenConverter.fromDollar( 200 ); D Slide 30 public double fromDollar( double dollar ) { double amount, fee; fee = exchangeRate - feeRate; amount = dollar * fee; return amount; } At D after fromDollar yenConverter Currency Converter amt 24846.3 exchangeRate 129.2315 feeRate 5.0 State of Memory D. Memory space for local variables and parameters is deallocated upon exiting the fromDollar method. 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 Slide 31 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 Passing Parameters Slide 32 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-byvalue 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 Pass-By-Value Scheme Code A x = 10; y = 20; tester.myMethod( x, y ); Slide 33 public void myMethod( int one, float two ) { one = 25; two = 35.4f; } At A before myMethod x State of Memory y 10 A. Local variables do 20 10 not exist before the method execution Slide 34 Pass-By-Value Scheme Code x = 10; y = 20; tester.myMethod( x, y ); public void myMethod( int one, float two ) { one = 25; two = 35.4f; } Values are copied at x State of Memory y 10 20 10 one two B B 10 B. The values of 20.0f 10 arguments are copied to the parameters. Slide 35 Pass-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 After C x State of Memory y 10 20 10 is executed one two 25 10 C. The values of 35.4f 10 parameters are changed. Pass-By-Value Scheme Slide 36 Code x = 10; y = 20; tester.myMethod( x, y ); D public void myMethod( int one, float two ) { one = 25; two = 35.4f; } At D after myMethod x State of Memory y 10 D. Parameters are 20 10 erased. Arguments remain unchanged. Constructors Slide 37 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> } Modifier public Class Name BankAccount ( Parameter ) ) Currently, BankAccount’s constructor has no arguments and does nothing. { Statements } Multiple Constructors A class can include multiple constructors without any problem, as long as the constructors defined for the class have either Slide 39 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 public MyClass( value ) { … } ) { … } public MyClass( float value ) { … } These constructors will not conflict with each other, and therefore, valid. public MyClass( String name, float value ) { … } A Common Misconception Slide 40 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; } Give the parameter a different name in order to be clear. (We’ll discuss another way later.) … methods (not shown) … } Don’t forget to set the field through an assignment statement. Access Modifiers Slide 42 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”) in another class … class Test { public int memberOne; private int memberTwo; } Test myTest = new MyTest(); myTest.memberOne = 10; myTest.memberTwo = 20; Keeping fields private Slide 43 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