Presentation is loading. Please wait.

Presentation is loading. Please wait.

©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 1 Chapter 7: More about Methods 1 Chapter 7 More about Methods.

Similar presentations


Presentation on theme: "©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 1 Chapter 7: More about Methods 1 Chapter 7 More about Methods."— Presentation transcript:

1 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 1 Chapter 7: More about Methods 1 Chapter 7 More about Methods

2 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 2 Chapter 7: More about Methods 2 Formal and actual parameters xFormal parameters: class BankAccount { public void deposit(double amount) { balance += amount; }... } Actual parameters: harrysChecking.deposit(allowance - 200)

3 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 3 Chapter 7: More about Methods 3 Figure 1 Parameter Passing

4 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 4 Chapter 7: More about Methods 4 Object parameters public void transfer(BankAccount other, double amount) { withdraw(amount); other.deposit(amount); } Call with an object and a number parameter: double allowance = 800; momsSavings.transfer(harrysChecking, allowance);

5 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 5 Chapter 7: More about Methods 5 Figure 2 Object References and Number Parameters

6 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 6 Chapter 7: More about Methods 6 Accessor and mutator methods Accessor: does not change the state of the implicit parameter (e.g. getBalance ) Mutator: changes the state of the implicit parameter (e.g. deposit ) Immutable class: all methods are accessors (e.g. String )

7 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 7 Chapter 7: More about Methods 7 Side effect Any observable change outside the implicit parameter Example: modify other parameter (e.g. transfer ) Example: printing in method: public void deposit(double amount) { if (amount < 0) System.out.println("Bad value");... }

8 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 8 Chapter 7: More about Methods 8 Minimize side effects Excellent: No modifications ( getBalance ) Good: Mutators that only change the implicit parameter ( deposit ) Fair: Methods that change an explicit parameter ( transfer ) Poor: Methods with other side effects (changing static variables, printing)

9 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 9 Chapter 7: More about Methods 9 Static methods Method with no implicit parameter Doesn't act on an object Typical example: all parameters are numbers: Recall that x and y are approximately equal if |x - y|  max(|x|, |y|) public static boolean approxEqual (double x, double y) { return Math.abs(x - y) <= EPSILON * Math.max(Math.abs(x), Math.abs(y)); }

10 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 10 Chapter 7: More about Methods 10 Static methods In Java, every method must be in a class: class Numeric { public static boolean approxEqual(double x, double y) {... } } Call with class name instead of object: if (Numeric.approxEqual(a, b))...

11 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 11 Chapter 7: More about Methods 11 Can't modify number parameters public static void updateBalance (double balance, double interestRate) { double interest = balance * interestRate / 100; balance = balance + interest; } Won't work: double savings = 10000; double rate = 5; updateBalance(savings, rate);

12 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 12 Chapter 7: More about Methods 12 Figure 3 A Method Cannot Modify Numeric Parameters

13 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 13 Chapter 7: More about Methods 13 Can modify object parameter state public static void updateBalance (BankAccount account, double interestRate) { double interest = account.getBalance() * interestRate / 100; account.deposit(interest); } BankAccount collegeFund = new BankAccount(10000); double rate = 5; updateBalance(collegeFund, rate);

14 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 14 Chapter 7: More about Methods 14 Figure 4 A Method Can Modify the State of Object Parameters

15 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 15 Chapter 7: More about Methods 15 Can't modify object param content public static chooseAccount(BankAccount betterAccount, BankAccount candidate1, BankAccount candidate2) { if (candidate1.getBalance() > candidate2.getBalance()) betterAccount = candidate1; else betterAccount = candidate2; } BankAccount collegeFund = new BankAccount(10000); BankAccount momsSavings = new BankAccount(8000); BankAccount myAccount = null; // won't work chooseAccount(myAccount,momsSavings,collegeFund);

16 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 16 Chapter 7: More about Methods 16 Figure 5 A Method Cannot Replace Object Parameters

17 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 17 Chapter 7: More about Methods 17 Static variables One variable per class, not per object Example: last assigned account number— class property, not object property public class BankAccount {... private double balance; private int accountNumber; private static int lastAssignedNumber; }

18 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 18 Chapter 7: More about Methods 18 Static variables public BankAccount() { lastAssignedNumber++; accountNumber = lastAssignedNumber; } Static variable initialization: class BankAccount {... private static int lastAssignedNumber = 0; } Static constants: Math.PI

19 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 19 Chapter 7: More about Methods 19 Figure 6 Instance Variables and a Static Variable

20 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 20 Chapter 7: More about Methods 20 Variable types Instance variables Static variables Local variables Parameter variables

21 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 21 Chapter 7: More about Methods 21 Scope Class scope—defined in class (instance or static variable) Block scope—defined in block (local variable) Shadowing class BankAccount { public BankAccount(double initialBal) { double balance = initialBal; } private double balance; }

22 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 22 Chapter 7: More about Methods 22 Method Comments /** Tests whether two floating-point numbers are equal except for roundoff @param x a floating-point number @param y a floating-point number @return true if x and y are approximately equal */ public static boolean approxEqual(double x, double y) {... }

23 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 23 Chapter 7: More about Methods 23 Class comments /** A class that stores the position and speed of a simulated cannon ball */ public class CannonBall {... } Extract comments with javadoc utility: javadoc MyProg.java

24 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 24 Chapter 7: More about Methods 24 Figure 7 An HTML Page Produced by the javadoc Utility

25 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 25 Chapter 7: More about Methods 25 Program Fac.java public class Fac { public static void main(String[] args) { ConsoleReader console = new ConsoleReader(System.in); System.out.println("Please enter a number:"); int n = console.readInt(); System.out.println(n + "! = ” + factorial(n)); }

26 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 26 Chapter 7: More about Methods 26 Preconditions What should a method do when it is called with bad parameters? Math.sqrt(-1); account.deposit(-1000); Do nothing? Terminate program? Return error condition to caller?

27 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 27 Chapter 7: More about Methods 27 Preconditions Establish precondition: @param amount the amount of money to deposit; must be > 0 Throw exception if precondition is violated: if (amount <= 0) throw new IllegalArgumentException(); Caller's responsibility: call the methods with parameters that fulfill the precondition Your responsibility: compute the right results when the parameters fulfill the precondition

28 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 28 Chapter 7: More about Methods 28 Recursion n! = 1  2  3 ...  n 0! = 1 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 Number of permutations of n symbols 3! = 6: car, rac, arc, acr, rca, cra

29 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 29 Chapter 7: More about Methods 29 Recursion No magic... operation: public static int factorial(int ) { return 1 * 2 * 3 *... * n; } That's not how I computed the table—I used n! = (n - 1)!  n public static int factorial(int ) { return factorial(n - 1) * n; } Almost right—recursion must terminate.

30 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 30 Chapter 7: More about Methods 30 Recursion Every recursive call must simplify the computation in some way There must be special cases to handle the simplest computations factorial(4) calls factorial(3) factorial(3) calls factorial(2) factorial(2) calls factorial(1) factorial(1) calls factorial(0) factorial(0) returns 1 factorial(1) returns 1 * 1 = 1 factorial(2) returns 1 * 2 = 2 factorial(3) returns 2 * 3 = 6 factorial(4) returns 6 * 4 = 24

31 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 31 Chapter 7: More about Methods 31 /** Computes the factorial of an integer. @param n an integer >= 0 @return n! */ public static int factorial(int n) { if (n == 0) return 1; else { int result = n * factorial(n - 1); return result; }

32 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 32 Chapter 7: More about Methods 32 Figure 11 Towers of Hanoi


Download ppt "©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 1 Chapter 7: More about Methods 1 Chapter 7 More about Methods."

Similar presentations


Ads by Google