Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


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

1 Objects & Methods Defining Classes

2 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

3 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) xyz (null) BankAccount x, y, z; x = new BankAccount(); y = x; z = new BankAccount(); y = z; x = z;

4 Slide 4 Reference Variables Revisited xyz (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)

5 Slide 5 Reference Variables Revisited xyz (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)

6 Slide 6 Reference Variables Revisited xyz 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)

7 Slide 7 Reference Variables Revisited BankAccount x, y, z; x = new BankAccount(); y = x; z = new BankAccount(); y = z; x = z; xyz Think of Objects as balloons! references are like strings (aka “handles”) Idea from “Beginning Java Objects” by Jacquie Barker (Wrox)

8 Slide 8 Reference Variables Revisited BankAccount x, y, z; x = new BankAccount(); y = x; z = new BankAccount(); y = z; x = z; xyz Think of Objects as balloons! references are like strings (aka “handles”) Idea from “Beginning Java Objects” by Jacquie Barker (Wrox)

9 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; xyz

10 Slide 10 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(); 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!)

11 Objects (Part 2) Defining Classes

12 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

13 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”

14 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

15 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!)

16 Slide 16 Method Declaration ( ) { } public void deposit ( int amount ) { balance += amount; } Statements Modifier Return Type Method Name Parameter

17 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 ; public int getBalance( ) { return balance; }

18 Slide 18 How Methods Work BankApplet.java State of Memory … int aliceBalance = aliceAccount.getBalance(); … aliceAccount BankAccount aliceBalance 100 int balance 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 When the line above is run …

19 Slide 19 How Methods Work BankApplet.java State of Memory … int aliceBalance = aliceAccount.getBalance(); … aliceAccount getBalance() BankAccount aliceBalance 100 int balance 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 When the line above is run …

20 Slide 20 How Methods Work BankApplet.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 100 int balance 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 When the line above is run …

21 Slide 21 How Methods Work BankApplet.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 100 int balance 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 When the line above is run …

22 Slide 22 How Methods Work BankApplet.java State of Memory … int aliceBalance = aliceAccount.getBalance(); … aliceAccount getBalance() BankAccount aliceBalance 100 int balance 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 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; }

23 Slide 23 How Methods Work BankApplet.java State of Memory … int aliceBalance = aliceAccount.getBalance(); … public int getBalance() { return balance; } BankAccount.java aliceAccount getBalance() BankAccount aliceBalance 100 int balance 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 When the line above is run … 100

24 Slide 24 How Methods Work BankApplet.java State of Memory … int aliceBalance = aliceAccount.getBalance(); … public int getBalance() { return balance; } BankAccount.java aliceAccount getBalance() BankAccount aliceBalance 100 int balance 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 When the line above is run … 100

25 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

26 Slide 26 Sample Method public double fromDollar( double dollar ) { double amount, fee; fee = exchangeRate - feeRate; amount= dollar * fee; return amount; } Parameter Local Variables Fields * * Although not shown here, exchangeRate and feeRate were declared inside the CurrencyConverter class, but outside any methods From Wu’s CurrencyConverter class …

27 Slide 27 Local Variables Example Code State of Memory amt = yenConverter.fromDollar( 200 ); public double fromDollar( double dollar ) { double amount, fee; fee = exchangeRate - feeRate; amount = dollar * fee; return amount; } A A A. A. fromDollar’s local variables (amount and fee) do not exist before the method call At before fromDollar A A Currency Converter 129.2315 exchangeRate 5.0 feeRate yenConverter amt 0.0

28 Slide 28 Local Variables Example Code amt = yenConverter.fromDollar( 200 ); public double fromDollar( double dollar ) { double amount, fee; fee = exchangeRate - feeRate; amount = dollar * fee; return amount; } B B B. B. Memory space is allocated for the local variables and parameter. Parameter’s value is copied from the argument. After is executed B B dollar 200.0 amount fee State of Memory Currency Converter 129.2315 exchangeRate 5.0 feeRate yenConverter amt 0.0

29 Slide 29 amount fee Local Variables Example Code amt = yenConverter.fromDollar( 200 ); public double fromDollar( double dollar ) { double amount, fee; fee = exchangeRate - feeRate; amount = dollar * fee; return amount; } C C C. C. Computed values are assigned to the local variables. After is executed C C dollar 24846.3 200.0 124.2315 Currency Converter 129.2315 exchangeRate 5.0 feeRate yenConverter amt 0.0 State of Memory

30 Slide 30 amt 24846.3 Local Variables Example Code amt = yenConverter.fromDollar( 200 ); public double fromDollar( double dollar ) { double amount, fee; fee = exchangeRate - feeRate; amount = dollar * fee; return amount; } D D D. D. Memory space for local variables and parameters is deallocated upon exiting the fromDollar method. At after fromDollar D D Currency Converter 129.2315 exchangeRate 5.0 feeRate yenConverter State of Memory

31 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

32 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

33 Slide 33 Pass-By-Value Scheme State of Memory public void myMethod( int one, float two ) { one = 25; two = 35.4f; } A A A. A. Local variables do not exist before the method execution At before myMethod A A Code x = 10; y = 20; tester.myMethod( x, y ); xx 10 y 20

34 Slide 34 Pass-By-Value Scheme State of Memory B. B. The values of arguments are copied to the parameters. Values are copied at B B public void myMethod( int one, float two ) { one = 25; two = 35.4f; } Code x = 10; y = 20; tester.myMethod( x, y ); B B xx 10 y 20 one 10 two 1020.0f

35 Slide 35 Pass-By-Value Scheme C C State of Memory C. C. The values of parameters are changed. After is executed C C public void myMethod( int one, float two ) { one = 25; two = 35.4f; } Code x = 10; y = 20; tester.myMethod( x, y ); xx 10 y 20 one 1025 two 1035.4f

36 Slide 36 Pass-By-Value Scheme Code D D State of Memory D. D. Parameters are erased. Arguments remain unchanged. At after myMethod D D public void myMethod( int one, float two ) { one = 25; two = 35.4f; } x = 10; y = 20; tester.myMethod( x, y ); xx 10 y 20

37 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

38 Slide 38 Defining Constructors A constructor will have the following form: public ( ) { } public BankAccount ( ) { } Currently, BankAccount’s constructor has no arguments and does nothing. Statements Modifier Class Name Parameter

39 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.

40 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.

41 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.

42 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 …

43 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


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

Similar presentations


Ads by Google