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

Slides:



Advertisements
Similar presentations
Lecture 9: More on objects, classes, strings discuss hw3 assign hw4 default values for variables scope of variables and shadowing null reference and NullPointerException.
Advertisements

IMPLEMENTING CLASSES Chapter 3. Black Box  Something that magically does its thing!  You know what it does but not how.  You really don’t care how.
Designing Classes Chapter 8. Classes Collection of objects Objects are not actions Class names – Nouns Method names – Verbs What Makes a Good Class Represent.
1 Objects, Classes, and Packages “Static” Classes Introduction to Classes Object Variables and Object References Instantiating Objects Using Methods in.
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 1 Chapter 6: Iteration 1 Chapter 6 Iteration.
I NHERITANCE Chapter 10. I NHERITANCE Mechanism for enhancing existing classes You need to implement a new class You have an existing class that represents.
Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.
Our BankAccount class should define three methods  deposit  withdraw  getBalance How a programmer will carry out these operations?  We assume that.
Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.
Chapter 13 Inheritance. An Introduction to Inheritance Inheritance: extend classes by adding methods and fields (variables) Example: Savings account =
CHAPTER 11 INHERITANCE CHAPTER GOALS To understand how to inherit and override superclass methods To be able to invoke superclass constructors To learn.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter Three - Implementing Classes.
Chapter 9 – Inheritance Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Chapter 2 – An Introduction to Objects and Classes Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Chapter 8 Designing Classes. Assignment Chapter 9 Review Exercises (Written)  R8.1 – 8.3, 8.5 – 8.7, 8. 10, 8.11, 8.13, 8.15, 8.19, 8.20 Due Friday,
Chapter Goals To learn how to choose appropriate classes to implement
Lecture 3: Topics If-then-else Operator precedence While loops Static methods Recursion.
Chapter 7 Designing Classes Goals  To learn how to choose appropriate classes to implement  To understand the concepts of cohesion and coupling  To.
CSM-Java Programming-I Spring,2005 Class Design Lesson - 4.
Inheritance Part III. Lecture Objectives To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke.
Class Design CSC 171 FALL 2004 LECTURE 11. READING Read Chapter 7 It’s abstract But it should help with project #1.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 8: Classes and Objects.
Chapter 3 Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To understand.
Using Objects Object: an entity in your program that you can manipulate Attributes Methods Method: consists of a sequence of instructions that can access.
Inheritance Part II. Lecture Objectives To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass.
Previous Exam 1.0. Question 1 - a Is the following statement true or false? Briefly explain your answer. A && B is the same as B && A for any Boolean.
Understanding class definitions Looking inside classes.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Week 4 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Inheritance.
Often categorize concepts into hierarchies: Inheritance Hierarchies Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. if (amount
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 8: Testing and Debugging 1 Chapter 8 Testing and Debugging.
Classes CS 21a: Introduction to Computing I First Semester,
Class Design: Handling Errors Reading: 2 nd Ed: Chapter 15 3 rd Ed: Chapter 11 Exercises 2 nd Ed: P15.5, P15.6 (Hint: look at documentation for Scanner.
Exceptions. Exception Abnormal event occurring during program execution Examples –Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
ACO 101: Introduction to Computer Science Anatomy Part 2: Methods.
Classes All Java code must be inside classes Class types – Utility classes Used to store constants, utility methods, etc. – Driver classes – Abstract Data.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. A class represents a single concept from the problem domain Name.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 10 - Interfaces.
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 1 Chapter 5: Decisions 1 Chapter 5 Decisions.
CHAPTER 11 INHERITANCE. CHAPTER GOALS To understand how to inherit and override superclass methods To be able to invoke superclass constructors To learn.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Encapsulation ◦ Blackbox concept Data and method(s) Hidden details InterfaceEffect(s) methods called class.
CS305j Introduction to Computing Classes II 1 Topic 24 Classes Part II "Object-oriented programming as it emerged in Simula 67 allows software structure.
Chapter 8: Designing Classes Accessors, Mutators, and Immutable Classes(8.3) Side Effects(8.4) Parameter Passing (Advanced Topic 8.1) Preconditions and.
Bank Account Example public class BankAccount { private double balance; public static int totalAccounts = 0; public BankAccount() { balance = 0; totalAccounts++;
Chapter 9 – Designing Classes Goals Learning to design classes Learning to design classes Preconditions and postconditions for methods Preconditions.
Object Oriented Programming and Data Abstraction Rowan University Earl Huff.
Week 13 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Chapter 7 Designing Classes. Chapter Goals  To learn how to choose appropriate classes to implement  To understand the concepts of cohesion and coupling.
CSH Intro. to Java. The Big Ideas in Computer Science Beyond programming Solving tough problems Creating extensible solutions Teams of “Computational.
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 3: An Introduction to Classes 1 Chapter 3 An Introduction to Classes.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter Three - Implementing Classes.
Chapter 9 – Designing Classes. Chapter Goals Discovering and learning to Design classes Discovering and learning to Design classes Preconditions and postconditions.
Chapter 3 Implementing Classes
Basic Class Structure. Class vs. Object class - a template for building an object –defines the instance data that the object will hold –defines instance.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Variable Scope & Lifetime
Lecture 3 John Woodward.
Chapter 7 User-Defined Methods.
Chapter 3 – Implementing Classes
Chapter Goals To become familiar with the process of implementing classes To be able to implement and test simple methods To understand the purpose and.
Chapter Three - Implementing Classes
Object initialization: constructors
د.سناء الصايغ الفصل الأول البرمجة الشيئية
More on Classes and Objects
JAVA CLASSES.
Classes CS 21a: Introduction to Computing I
Presentation transcript:

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

©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)

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

©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);

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

©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 )

©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");... }

©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)

©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)); }

©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))...

©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);

©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

©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);

©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

©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);

©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

©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; }

©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

©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

©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

©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; }

©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 x a floating-point y a floating-point true if x and y are approximately equal */ public static boolean approxEqual(double x, double y) {... }

©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

©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

©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)); }

©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?

©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 27 Chapter 7: More about Methods 27 Preconditions Establish 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

©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

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

©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

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

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