Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 4: Writing Classes Presentation slides for Java Software Solutions Foundations of Program Design Second Edition by John Lewis and William Loftus.

Similar presentations


Presentation on theme: "Chapter 4: Writing Classes Presentation slides for Java Software Solutions Foundations of Program Design Second Edition by John Lewis and William Loftus."— Presentation transcript:

1 Chapter 4: Writing Classes Presentation slides for Java Software Solutions Foundations of Program Design Second Edition by John Lewis and William Loftus Java Software Solutions is published by Addison-Wesley Presentation slides are copyright 2000 by John Lewis and William Loftus. All rights reserved. Instructors using the textbook may use and modify these slides for pedagogical purposes.

2 2 Objects b An object has: state - descriptive characteristicsstate - descriptive characteristics behaviors - what it can do (or be done to it)behaviors - what it can do (or be done to it) b For example, consider a coin that can be flipped so that it's face shows either "heads" or "tails" b The state of the coin is its current face (heads or tails) b The behavior of the coin is that it can be flipped b Note that the behavior of the coin might change its state

3 3 Classes b A class is a blueprint of an object b It is the model or pattern from which objects are created  For example, the String class is used to define String objects  Each String object contains specific characters (its state)  Each String object can perform services (behaviors) such as toUpperCase

4 Classes  The String class was provided for us by the Java standard class library b But we can also write our own classes that define specific objects that we need b For example, suppose we wanted to write a program that simulates the flipping of a coin  We could write a Coin class to represent a coin object

5 Classes b A class contains data declarations and method declarations int x, y; char ch; Data declarations Method declarations

6 Data Scope b The scope of data is the area in a program in which that data can be used (referenced) b Data declared at the class level can be used by all methods in that class b Data declared within a method can only be used in that method b Data declared within a method is called local data

7 Writing Methods b A method declaration specifies the code that will be executed when the method is invoked (or called) b When a method is invoked, the flow of control jumps to the method and executes its code b When complete, the flow returns to the place where the method was called and continues b The invocation may or may not return a value, depending on how the method was defined

8 myMethod(); myMethodcompute Method Control Flow b The called method could be within the same class, in which case only the method name is needed

9 doIt helpMe helpMe(); obj.doIt(); main Method Control Flow b The called method could be part of another class or object

10 The Coin Class  In our Coin class we could define the following data: face, an integer that represents the current faceface, an integer that represents the current face HEADS and TAILS, integer constants that represent the two possible statesHEADS and TAILS, integer constants that represent the two possible states b We might also define the following methods: a Coin constructor, to set up the objecta Coin constructor, to set up the object a flip method, to flip the coina flip method, to flip the coin a getFace method, to return the current facea getFace method, to return the current face a toString method, to return a string description for printinga toString method, to return a string description for printing

11 Coin Class public class Coin { private final int HEADS = 0; private final int HEADS = 0; private final int TAILS = 1; private final int TAILS = 1; private int face; private int face; public Coin () { public Coin () { flip(); flip(); } public void flip () { public void flip () { face = (int) (Math.random() * 2); face = (int) (Math.random() * 2); } public boolean isHeads () { public boolean isHeads () { return (face == HEADS); return (face == HEADS); } public String toString() { public String toString() { String faceName; String faceName; if (face == HEADS) if (face == HEADS) faceName = "Heads"; faceName = "Heads"; else else faceName = "Tails"; faceName = "Tails"; return faceName; return faceName; }}

12 Count Flips final int NUM_FLIPS = 1000; final int NUM_FLIPS = 1000; int heads = 0, tails = 0; int heads = 0, tails = 0; Coin myCoin = new Coin(); // instantiate the Coin object Coin myCoin = new Coin(); // instantiate the Coin object for (int count=1; count <= NUM_FLIPS; count++) for (int count=1; count <= NUM_FLIPS; count++) { myCoin.flip(); myCoin.flip(); if (myCoin.isHeads()) if (myCoin.isHeads()) heads++; heads++; else else tails++; tails++; } System.out.println ("The number flips: " + NUM_FLIPS); System.out.println ("The number flips: " + NUM_FLIPS); System.out.println ("The number of heads: " + heads); System.out.println ("The number of heads: " + heads); System.out.println ("The number of tails: " + tails); System.out.println ("The number of tails: " + tails);

13 The Coin Class b See CountFlips.java (page 179) CountFlips.java b See Coin.java (page 180) Coin.java  Once the Coin class has been defined, we can use it again in other programs as needed  Note that the CountFlips program did not use the toString method b A program will not necessarily use every service provided by an object

14 Instance Data  The face variable in the Coin class is called instance data because each instance (object) of the Coin class has its own b A class declares the type of the data, but it does not reserve any memory space for it  Every time a Coin object is created, a new face variable is created as well b The objects of a class share the method definitions, but they have unique data space b That's the only way two objects can have different states

15 Instance Data b See FlipRace.java (page 182) FlipRace.java face 0 coin1 int face; class Coin face 1 coin2

16 16 Encapsulation b You can take one of two views of an object: internal - the structure of its data, the algorithms used by its methodsinternal - the structure of its data, the algorithms used by its methods external - the interaction of the object with other objects in the programexternal - the interaction of the object with other objects in the program b From the external view, an object is an encapsulated entity, providing a set of specific services b These services define the interface to the object b Recall from Chapter 2 that an object is an abstraction, hiding details from the rest of the system

17 17 Encapsulation b An object should be self-governing b Any changes to the object's state (its variables) should be accomplished by that object's methods b We should make it difficult, if not impossible, for one object to "reach in" and alter another object's state b The user, or client, of an object can request its services, but it should not have to be aware of how those services are accomplished

18 18 Encapsulation b An encapsulated object can be thought of as a black box b Its inner workings are hidden to the client, which only invokes the interface methods Client Methods Data

19 19 Visibility Modifiers b In Java, we accomplish encapsulation through the appropriate use of visibility modifiers b A modifier is a Java reserved word that specifies particular characteristics of a method or data value  We've used the modifier final to define a constant  Java has three visibility modifiers: public, private, and protected  We will discuss the protected modifier later

20 20 Visibility Modifiers b Members of a class that are declared with public visibility can be accessed from anywhere b Members of a class that are declared with private visibility can only be accessed from inside the class b Members declared without a visibility modifier have default visibility and can be accessed by any class in the same package b Java modifiers are discussed in detail in Appendix F

21 21 Visibility Modifiers b As a general rule, no object's data should be declared with public visibility b Methods that provide the object's services are usually declared with public visibility so that they can be invoked by clients b Public methods are also called service methods b A method created simply to assist a service method is called a support method b Since a support method is not intended to be called by a client, it should not be declared with public visibility

22 Method Declarations Revisited b A method declaration begins with a method header char calc (int num1, int num2, String message) methodname returntype parameter list The parameter list specifies the type and name of each parameter The name of a parameter in the method declaration is called a formal argument

23 Method Declarations b The method header is followed by the method body char calc (int num1, int num2, String message) { int sum = num1 + num2; char result = message.charAt (sum); return result; } The return expression must be consistent with the return type sum and result are local data They are created each time the method is called, and are destroyed when it finishes executing

24 24 The return Statement b The return type of a method indicates the type of value that the method sends back to the calling location  A method that does not return a value has a void return type b The return statement specifies the value that will be returned b Its expression must conform to the return type

25 Parameters b Each time a method is called, the actual arguments in the invocation are copied into the formal arguments char calc (int num1, int num2, String message) { int sum = num1 + num2; char result = message.charAt (sum); return result; } ch = obj.calc (25, count, "Hello");

26 26 Constructors Revisited b Recall that a constructor is a special method that is used to set up a newly created object b When writing a constructor, remember that: it has the same name as the classit has the same name as the class it does not return a valueit does not return a value it has no return type, not even voidit has no return type, not even void it often sets the initial values of instance variablesit often sets the initial values of instance variables b The programmer does not have to define a constructor for a class

27 Writing Classes b See BankAccounts.java (page 188) BankAccounts.java b See Account.java (page 189) Account.java b An aggregate object is an object that contains references to other objects  An Account object is an aggregate object because it contains a reference to a String object (that holds the owner's name) b An aggregate object represents a has-a relationship b A bank account has a name

28 import java.text.NumberFormat; public class Account { private NumberFormat fmt = NumberFormat.getCurrencyInstance(); private NumberFormat fmt = NumberFormat.getCurrencyInstance(); private final double RATE = 0.045; // interest rate of 4.5% private final double RATE = 0.045; // interest rate of 4.5% private long acctNumber; private long acctNumber; private double balance; private double balance; private String name; private String name; // Sets up the account by defining its owner, account number, // Sets up the account by defining its owner, account number, // and initial balance. // and initial balance. public Account (String owner, long account, double initial) public Account (String owner, long account, double initial) { name = owner; name = owner; acctNumber = account; acctNumber = account; balance = initial; balance = initial; } // Validates the transaction, then deposits the specified amount // Validates the transaction, then deposits the specified amount // into the account. Returns the new balance. // into the account. Returns the new balance. public double deposit (double amount) public double deposit (double amount) { if (amount < 0) // deposit value is negative if (amount < 0) // deposit value is negative { System.out.println (); System.out.println (); System.out.println ("Error: Deposit amount is invalid."); System.out.println ("Error: Deposit amount is invalid."); System.out.println (acctNumber + " " + fmt.format(amount)); System.out.println (acctNumber + " " + fmt.format(amount)); } else else balance = balance + amount; balance = balance + amount; return balance; return balance; }

29 //----------------------------------------------------------------- //----------------------------------------------------------------- // Validates the transaction, then withdraws the specified amount // Validates the transaction, then withdraws the specified amount // from the account. Returns the new balance. // from the account. Returns the new balance. //----------------------------------------------------------------- //----------------------------------------------------------------- public double withdraw (double amount, double fee) public double withdraw (double amount, double fee) { amount += fee; amount += fee; if (amount < 0) // withdraw value is negative if (amount < 0) // withdraw value is negative { System.out.println (); System.out.println (); System.out.println ("Error: Withdraw amount is invalid."); System.out.println ("Error: Withdraw amount is invalid."); System.out.println ("Account: " + acctNumber); System.out.println ("Account: " + acctNumber); System.out.println ("Requested: " + fmt.format(amount)); System.out.println ("Requested: " + fmt.format(amount)); } else else if (amount > balance) // withdraw value exceeds balance if (amount > balance) // withdraw value exceeds balance { System.out.println (); System.out.println (); System.out.println ("Error: Insufficient funds."); System.out.println ("Error: Insufficient funds."); System.out.println ("Account: " + acctNumber); System.out.println ("Account: " + acctNumber); System.out.println ("Requested: " + fmt.format(amount)); System.out.println ("Requested: " + fmt.format(amount)); System.out.println ("Available: " + fmt.format(balance)); System.out.println ("Available: " + fmt.format(balance)); } else else balance = balance - amount; balance = balance - amount; return balance; return balance; } //----------------------------------------------------------------- //----------------------------------------------------------------- // Adds interest to the account and returns the new balance. // Adds interest to the account and returns the new balance. //----------------------------------------------------------------- //----------------------------------------------------------------- public double addInterest () public double addInterest () { balance += (balance * RATE); balance += (balance * RATE); return balance; return balance; }

30 Account.java cont. //----------------------------------------------------------------- //----------------------------------------------------------------- // Returns the current balance of the account. // Returns the current balance of the account. //----------------------------------------------------------------- //----------------------------------------------------------------- public double getBalance () public double getBalance () { return balance; return balance; } //----------------------------------------------------------------- //----------------------------------------------------------------- // Returns the account number. // Returns the account number. //----------------------------------------------------------------- //----------------------------------------------------------------- public long getAccountNumber () public long getAccountNumber () { return acctNumber; return acctNumber; } //----------------------------------------------------------------- //----------------------------------------------------------------- // Returns a one-line description of the account as a string. // Returns a one-line description of the account as a string. //----------------------------------------------------------------- //----------------------------------------------------------------- public String toString () public String toString () { return (acctNumber + "\t" + name + "\t" + fmt.format(balance)); return (acctNumber + "\t" + name + "\t" + fmt.format(balance)); }}

31 Using Account Class Account acct1 = new Account ("Ted Murphy", 72354, 102.56); Account acct1 = new Account ("Ted Murphy", 72354, 102.56); Account acct2 = new Account ("Jane Smith", 69713, 40.00); Account acct2 = new Account ("Jane Smith", 69713, 40.00); Account acct3 = new Account ("Edward Demsey", 93757, 759.32); Account acct3 = new Account ("Edward Demsey", 93757, 759.32); acct1.deposit (25.85); acct1.deposit (25.85); double smithBalance = acct2.deposit (500.00); double smithBalance = acct2.deposit (500.00); System.out.println ("Smith balance after deposit: " + System.out.println ("Smith balance after deposit: " + smithBalance); smithBalance); System.out.println ("Smith balance after withdrawal: " + System.out.println ("Smith balance after withdrawal: " + acct2.withdraw (430.75, 1.50)); acct2.withdraw (430.75, 1.50)); acct3.withdraw (800.00, 0.0); // exceeds balance acct3.withdraw (800.00, 0.0); // exceeds balance acct1.addInterest(); acct1.addInterest(); acct2.addInterest(); acct2.addInterest();

32 Writing Classes b Sometimes an object has to interact with other objects of the same type  For example, we might add two Rational number objects together as follows: r3 = r1.add(r2);  One object ( r1 ) is executing the method and another ( r2 ) is passed as a parameter b See RationalNumbers.java (page 196) RationalNumbers.java b See Rational.java (page 197) Rational.java

33 Using Rational Class Rational r1 = new Rational (6, 8); Rational r1 = new Rational (6, 8); Rational r2 = new Rational (1, 3); Rational r2 = new Rational (1, 3); Rational r3, r4, r5, r6, r7; Rational r3, r4, r5, r6, r7; System.out.println ("First rational number: " + r1); System.out.println ("First rational number: " + r1); if (r1.equals(r2)) if (r1.equals(r2)) System.out.println ("r1 and r2 are equal."); System.out.println ("r1 and r2 are equal."); else else System.out.println ("r1 and r2 are NOT equal."); System.out.println ("r1 and r2 are NOT equal."); r3 = r1.reciprocal(); r3 = r1.reciprocal(); System.out.println ("The reciprocal of r1 is: " + r3); System.out.println ("The reciprocal of r1 is: " + r3); r4 = r1.add(r2); r4 = r1.add(r2); r7 = r1.divide(r2); r7 = r1.divide(r2); System.out.println ("r1 + r2: " + r4); System.out.println ("r1 + r2: " + r4); System.out.println ("r1 / r2: " + r7); System.out.println ("r1 / r2: " + r7);

34 public class Rational { private int numerator, denominator; private int numerator, denominator; //----------------------------------------------------------------- //----------------------------------------------------------------- // Sets up the rational number by ensuring a nonzero denominator // Sets up the rational number by ensuring a nonzero denominator // and making only the numerator signed. // and making only the numerator signed. //----------------------------------------------------------------- //----------------------------------------------------------------- public Rational (int numer, int denom) public Rational (int numer, int denom) { if (denom == 0) if (denom == 0) denom = 1; denom = 1; // Make the numerator "store" the sign // Make the numerator "store" the sign if (denom < 0) if (denom < 0) { numer = numer * -1; numer = numer * -1; denom = denom * -1; denom = denom * -1; } numerator = numer; numerator = numer; denominator = denom; denominator = denom; reduce(); reduce(); }

35 public int getNumerator () public int getNumerator () { return numerator; return numerator; } public int getDenominator () public int getDenominator () { return denominator; return denominator; } public Rational reciprocal () public Rational reciprocal () { return new Rational (denominator, numerator); return new Rational (denominator, numerator); } public Rational add (Rational op2) public Rational add (Rational op2) { int commonDenominator = denominator * op2.getDenominator(); int commonDenominator = denominator * op2.getDenominator(); int numerator1 = numerator * op2.getDenominator(); int numerator1 = numerator * op2.getDenominator(); int numerator2 = op2.getNumerator() * denominator; int numerator2 = op2.getNumerator() * denominator; int sum = numerator1 + numerator2; int sum = numerator1 + numerator2; return new Rational (sum, commonDenominator); return new Rational (sum, commonDenominator); }

36 public Rational multiply (Rational op2) public Rational multiply (Rational op2) { int numer = numerator * op2.getNumerator(); int numer = numerator * op2.getNumerator(); int denom = denominator * op2.getDenominator(); int denom = denominator * op2.getDenominator(); return new Rational (numer, denom); return new Rational (numer, denom); } public Rational divide (Rational op2) public Rational divide (Rational op2) { return multiply (op2.reciprocal()); return multiply (op2.reciprocal()); } public boolean equals (Rational op2) public boolean equals (Rational op2) { return ( numerator == op2.getNumerator() && return ( numerator == op2.getNumerator() && denominator == op2.getDenominator() ); denominator == op2.getDenominator() ); } public String toString () { String result; String result; if (numerator == 0) if (numerator == 0) result = "0"; result = "0"; else else if (denominator == 1) if (denominator == 1) result = numerator + ""; result = numerator + ""; else else result = numerator + "/" + denominator; result = numerator + "/" + denominator; return result; return result; }

37 37 Overloading Methods b Method overloading is the process of using the same method name for multiple methods b The signature of each overloaded method must be unique b The signature includes the number, type, and order of the parameters b The compiler must be able to determine which version of the method is being invoked by analyzing the parameters b The return type of the method is not part of the signature

38 Overloading Methods float tryMe (int x) { return x +.375; } Version 1 float tryMe (int x, float y) { return x*y; } Version 2 result = tryMe (25, 4.32)Invocation

39 39 Overloaded Methods  The println method is overloaded: println (String s) println (String s) println (int i) println (int i) println (double d) println (double d) etc. etc.  The following lines invoke different versions of the println method: System.out.println ("The total is:"); System.out.println ("The total is:"); System.out.println (total); System.out.println (total);

40 40 Overloading Methods b Constructors can be overloaded b An overloaded constructor provides multiple ways to set up a new object b See SnakeEyes.java (page 203) SnakeEyes.java b See Die.java (page 204) Die.java

41 Snake Eyes final int ROLLS = 500; final int ROLLS = 500; int snakeEyes = 0, num1, num2; int snakeEyes = 0, num1, num2; Die die1 = new Die(); // creates a six-sided die Die die1 = new Die(); // creates a six-sided die Die die2 = new Die(20); // creates a twenty-sided die Die die2 = new Die(20); // creates a twenty-sided die for (int roll = 1; roll <= ROLLS; roll++) for (int roll = 1; roll <= ROLLS; roll++) { num1 = die1.roll(); num1 = die1.roll(); num2 = die2.roll(); num2 = die2.roll(); if (num1 == 1 && num2 == 1) // check for snake eyes if (num1 == 1 && num2 == 1) // check for snake eyes snakeEyes++; snakeEyes++; } System.out.println ("Number of rolls: " + ROLLS); System.out.println ("Number of rolls: " + ROLLS); System.out.println ("Number of snake eyes: " + snakeEyes); System.out.println ("Number of snake eyes: " + snakeEyes); System.out.println ("Ratio: " + (float)snakeEyes/ROLLS); System.out.println ("Ratio: " + (float)snakeEyes/ROLLS);

42 Die Class public class Die { private final int MIN_FACES = 4; private final int MIN_FACES = 4; private int numFaces; // number of sides on the die private int numFaces; // number of sides on the die private int faceValue; // current value showing on the die private int faceValue; // current value showing on the die // Defaults to a six-sided die. Initial face value is 1. // Defaults to a six-sided die. Initial face value is 1. public Die () { public Die () { numFaces = 6; numFaces = 6; faceValue = 1; faceValue = 1; } // Explicitly sets the size of the die. Defaults to a size of // Explicitly sets the size of the die. Defaults to a size of // six if the parameter is invalid. Initial face value is 1. // six if the parameter is invalid. Initial face value is 1. public Die (int faces) { public Die (int faces) { if (faces < MIN_FACES) if (faces < MIN_FACES) numFaces = 6; numFaces = 6; else else numFaces = faces; numFaces = faces; faceValue = 1; faceValue = 1; }

43 Die Cont. //----------------------------------------------------------------- //----------------------------------------------------------------- // Rolls the die and returns the result. // Rolls the die and returns the result. //----------------------------------------------------------------- //----------------------------------------------------------------- public int roll () public int roll () { faceValue = (int) (Math.random() * numFaces) + 1; faceValue = (int) (Math.random() * numFaces) + 1; return faceValue; return faceValue; } //----------------------------------------------------------------- //----------------------------------------------------------------- // Returns the current die value. // Returns the current die value. //----------------------------------------------------------------- //----------------------------------------------------------------- public int getFaceValue () public int getFaceValue () { return faceValue; return faceValue; }}

44 The StringTokenizer Class  The next example makes use of the StringTokenizer class, which is defined in the java.util package  A StringTokenizer object separates a string into smaller substrings (tokens) b By default, the tokenizer separates the string at white space  The StringTokenizer constructor takes the original string to be separated as a parameter  Each call to the nextToken method returns the next token in the string

45 Method Decomposition b A method should be relatively small, so that it can be readily understood as a single entity b A potentially large method should be decomposed into several smaller methods as needed for clarity b Therefore, a service method of an object may call one or more support methods to accomplish its goal b See PigLatin.java (page 207) PigLatin.java b See PigLatinTranslator.java (page 208) PigLatinTranslator.java

46 Pig Latin String st = "A method should be relatively small, so that it can be readily understood as a single entity"; PigLatinTranslator translator = new PigLatinTranslator(); String result = translator.translate (st); System.out.println(result);output: ayay ethodmay ouldshay ebay elativelyray all,smay osay atthay ityay ancay ebay e adilyray understoodyay asyay ayay inglesay entityyay

47 PigLatinTranslator import java.util.StringTokenizer; public class PigLatinTranslator { //----------------------------------------------------------------- //----------------------------------------------------------------- // Translates a sentence of words into Pig Latin. // Translates a sentence of words into Pig Latin. //----------------------------------------------------------------- //----------------------------------------------------------------- public String translate (String sentence) public String translate (String sentence) { String result = ""; String result = ""; sentence = sentence.toLowerCase(); sentence = sentence.toLowerCase(); StringTokenizer tokenizer = new StringTokenizer (sentence); StringTokenizer tokenizer = new StringTokenizer (sentence); while (tokenizer.hasMoreTokens()) while (tokenizer.hasMoreTokens()) { result += translateWord (tokenizer.nextToken()); result += translateWord (tokenizer.nextToken()); result += " "; result += " "; } return result; return result; }

48 PigLatinTranslator //----------------------------------------------------------------- //----------------------------------------------------------------- // Translates one word into Pig Latin. If the word begins with a // Translates one word into Pig Latin. If the word begins with a // vowel, the suffix "yay" is appended to the word. Otherwise, // vowel, the suffix "yay" is appended to the word. Otherwise, // the first letter or two are moved to the end of the word, // the first letter or two are moved to the end of the word, // and "ay" is appended. // and "ay" is appended. //----------------------------------------------------------------- //----------------------------------------------------------------- private String translateWord (String word) private String translateWord (String word) { String result = ""; String result = ""; if (beginsWithVowel(word)) if (beginsWithVowel(word)) result = word + "yay"; result = word + "yay"; else else if (beginsWithBlend(word)) if (beginsWithBlend(word)) result = word.substring(2) + word.substring(0,2) + "ay"; result = word.substring(2) + word.substring(0,2) + "ay"; else else result = word.substring(1) + word.charAt(0) + "ay"; result = word.substring(1) + word.charAt(0) + "ay"; return result; return result; }

49 PigLatinTranslator //----------------------------------------------------------------- //----------------------------------------------------------------- // Determines if the specified word begins with a vowel. // Determines if the specified word begins with a vowel. //----------------------------------------------------------------- //----------------------------------------------------------------- private boolean beginsWithVowel (String word) private boolean beginsWithVowel (String word) { String vowels = "aeiou"; String vowels = "aeiou"; char letter = word.charAt(0); char letter = word.charAt(0); return (vowels.indexOf(letter) != -1); return (vowels.indexOf(letter) != -1); }


Download ppt "Chapter 4: Writing Classes Presentation slides for Java Software Solutions Foundations of Program Design Second Edition by John Lewis and William Loftus."

Similar presentations


Ads by Google