Download presentation
Presentation is loading. Please wait.
Published byArline Lynch Modified over 9 years ago
1
INF 523Q Chapter 4: Writing Classes
2
2 b We've been using predefined classes. Now we will learn to write our own classes to define new objects b Chapter 4 focuses on: class declarationsclass declarations method declarationsmethod declarations instance variablesinstance variables encapsulationencapsulation method overloadingmethod overloading
3
3 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
4
4 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
5
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
6
Classes b A class contains data declarations and method declarations int x, y; char ch; Data declarations Method declarations
7
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
8
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
9
myMethod(); myMethodcompute Method Control Flow b The called method could be within the same class, in which case only the method name is needed
10
doIt helpMe helpMe(); obj.doIt(); main Method Control Flow b The called method could be part of another class or object
11
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 b See Coin.java (page 180) Coin.java b See CountFlips.java (page 179) CountFlips.java
12
Coin.java b //****************************************************************** b // Coin.java Author: Lewis and Loftus b // Represents a coin with two sides that can be flipped. b //****************************************************************** b public class Coin b { b public final int HEADS = 0; b public final int TAILS = 1; b private int face; b // Sets up the coin by flipping it initially. b public Coin () b { b flip(); b } b // Flips the coin by randomly choosing a face. b public void flip () b { b face = (int) (Math.random() * 2); b }
13
Coin.java (cont.) b // Returns the current face of the coin as an integer. b public int getFace () b { b return face; b } b // Returns the current face of the coin as a string. b public String toString() b { b String faceName; b if (face == HEADS) b faceName = "Heads"; b else b faceName = "Tails"; b return faceName; b }
14
CountFlips.java b //****************************************************************** b // CountFlips.java Author: Lewis and Loftus b // Demonstrates the use of a programmer-defined class. b //****************************************************************** b import Coin; b public class CountFlips b { b // Flips a coin multiple times and counts the number of heads and tails that result. b public static void main (String[] args) b { b final int NUM_FLIPS = 1000; b int heads = 0, tails = 0; b Coin myCoin = new Coin(); // instantiate the Coin object b for (int count=1; count <= NUM_FLIPS; count++)
15
CountFlips.java (cont.) b { b myCoin.flip(); b if (myCoin.getFace() == myCoin.HEADS) b heads++; b else b tails++; b } b System.out.println ("The number flips: " + NUM_FLIPS); b System.out.println ("The number of heads: " + heads); b System.out.println ("The number of tails: " + tails); b }
16
The Coin Class 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
17
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
18
Instance Data b See FlipRace.java (page 182) FlipRace.java face 0 coin1 int face; class Coin face 1 coin2
19
FlipRace.java b //******************************************************************** b // FlipRace.java Author: Lewis and Loftus b // Demonstrates the existence of separate data space in multiple b // instantiations of a programmer-defined class. b //******************************************************************** b import Coin; b public class FlipRace b { b // Flips two coins until one of them comes up heads a set number of times in a row. b public static void main (String[] args) b { b final int GOAL = 3; b int count1 = 0, count2 = 0; b // Create two separate coin objects b Coin coin1 = new Coin(); b Coin coin2 = new Coin(); b while (count1 < GOAL && count2 < GOAL) b { b coin1.flip(); b coin2.flip();
20
FlipRace.java (cont.) b // Print the flip results (uses Coin's toString method) b System.out.print ("Coin 1: " + coin1); b System.out.println (" Coin 2: " + coin2); b // Increment or reset the counters b count1 = (coin1.getFace() == coin1.HEADS) ? count1+1 : 0; b count2 = (coin2.getFace() == coin2.HEADS) ? count2+1 : 0; b } b // Determine the winner b if (count1 < GOAL) b System.out.println ("Coin 2 Wins!"); b else b if (count2 < GOAL) b System.out.println ("Coin 1 Wins!"); b else b System.out.println ("It's a TIE!"); b }
21
21 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
22
22 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
23
23 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
24
24 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
25
25 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
26
26 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
27
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
28
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
29
29 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
30
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");
31
31 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
32
Writing Classes b See Account.java (page 189) Account.java b See BankAccounts.java (page 188) BankAccounts.java
33
Account.java b //******************************************************************** b // Account.java Author: Lewis and Loftus b // Represents a bank account with basic services such as deposit and withdraw. b //******************************************************************** b import java.text.NumberFormat; b public class Account b { b private NumberFormat fmt = NumberFormat.getCurrencyInstance(); b private final double RATE = 0.045; // interest rate of 4.5% b private long acctNumber; b private double balance; b private String name; b // Sets up the account by defining its owner, account number, b // and initial balance. b public Account (String owner, long account, double initial) b { b name = owner; b acctNumber = account; b balance = initial; b }
34
Account.java (cont.) b // Validates the transaction, then deposits the specified amount b // into the account. Returns the new balance. b public double deposit (double amount) b { b if (amount < 0) // deposit value is negative b { b System.out.println (); b System.out.println ("Error: Deposit amount is invalid."); b System.out.println (acctNumber + " " + fmt.format(amount)); b } b else b balance = balance + amount; b return balance; b } b // Validates the transaction, then withdraws the specified amount b // from the account. Returns the new balance. b public double withdraw (double amount, double fee) b { b amount += fee;
35
Account.java (cont.) b if (amount < 0) // withdraw value is negative b { b System.out.println (); b System.out.println ("Error: Withdraw amount is invalid."); b System.out.println ("Account: " + acctNumber); b System.out.println ("Requested: " + fmt.format(amount)); b } b else b if (amount > balance) // withdraw value exceeds balance b { b System.out.println (); b System.out.println ("Error: Insufficient funds."); b System.out.println ("Account: " + acctNumber); b System.out.println ("Requested: " + fmt.format(amount)); b System.out.println ("Available: " + fmt.format(balance)); b } b else b balance = balance - amount; b return balance; b }
36
Account.java (cont.) b // Adds interest to the account and returns the new balance. b public double addInterest () b { b balance += (balance * RATE); b return balance; b } b // Returns the current balance of the account. b public double getBalance () b { b return balance; b } b // Returns the account number. b public long getAccountNumber () b { b return acctNumber; b } b // Returns a one-line description of the account as a string. b public String toString () b { b return (acctNumber + "\t" + name + "\t" + fmt.format(balance)); } }
37
BankAccounts.java b //******************************************************************** b // BankAccounts.java Author: Lewis and Loftus b // Driver to exercise the use of multiple Account objects. b //******************************************************************** b import Account; b public class BankAccounts b { b // Creates some bank accounts and requests various services. b public static void main (String[] args) b { b Account acct1 = new Account ("Ted Murphy", 72354, 102.56); b Account acct2 = new Account ("Jane Smith", 69713, 40.00); b Account acct3 = new Account ("Edward Demsey", 93757, 759.32); b acct1.deposit (25.85); b double smithBalance = acct2.deposit (500.00); b System.out.println ("Smith balance after deposit: " + b smithBalance);
38
BankAccounts.java (cont.) b System.out.println ("Smith balance after withdrawal: " + b acct2.withdraw (430.75, 1.50)); b acct3.withdraw (800.00, 0.0); // exceeds balance b acct1.addInterest(); b acct2.addInterest(); b acct3.addInterest(); b System.out.println (); b System.out.println (acct1); b System.out.println (acct2); b System.out.println (acct3); b }
39
Writing Classes 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
40
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 Rational.java (page 197) Rational.java b See RationalNumbers.java (page 196) RationalNumbers.java
41
Rational.java b //******************************************************************** b // Rational.java Author: Lewis and Loftus b // Represents one rational number with a numerator and denominator. b //******************************************************************** b public class Rational b { b private int numerator, denominator; b // Sets up the rational number by ensuring a nonzero denominator b // and making only the numerator signed. b public Rational (int numer, int denom) b { b if (denom == 0) b denom = 1; b // Make the numerator "store" the sign b if (denom < 0) b { b numer = numer * -1; b denom = denom * -1; b } b numerator = numer; b denominator = denom; b reduce(); }
42
Rational.java (cont.) b // Adds this rational number to the one passed as a parameter. b // A common denominator is found by multiplying the individual b // denominators. b public Rational add (Rational op2) b { b int commonDenominator = denominator * op2.getDenominator(); b int numerator1 = numerator * op2.getDenominator(); b int numerator2 = op2.getNumerator() * denominator; b int sum = numerator1 + numerator2; b return new Rational (sum, commonDenominator); b } b // Subtracts the rational number passed as a parameter from this b // rational number. b public Rational subtract (Rational op2) b { b int commonDenominator = denominator * op2.getDenominator(); b int numerator1 = numerator * op2.getDenominator(); b int numerator2 = op2.getNumerator() * denominator; b int difference = numerator1 - numerator2; b return new Rational (difference, commonDenominator); b }
43
Rational.java (cont.) b // Multiplies this rational number by the one passed as a parameter. b public Rational multiply (Rational op2) b { b int numer = numerator * op2.getNumerator(); b int denom = denominator * op2.getDenominator(); b return new Rational (numer, denom); b } b // Divides this rational number by the one passed as a parameter b // by multiplying by the reciprocal of the second rational. b public Rational divide (Rational op2) b { b return multiply (op2.reciprocal()); b } b // Returns the reciprocal of this rational number. b public Rational reciprocal () b { b return new Rational (denominator, numerator); b } b // Returns the numerator of this rational number. b public int getNumerator () b { return numerator; }
44
Rational.java (cont.) b // Returns the denominator of this rational number. b public int getDenominator () b { return denominator; } b // Determines if this rational number is equal to the one passed b // as a parameter. Assumes they are both reduced. b public boolean equals (Rational op2) b { b return ( numerator == op2.getNumerator() && b denominator == op2.getDenominator() ); b } b // Returns this rational number as a string. b public String toString () b { b String result; b if (numerator == 0) b result = "0"; b else b if (denominator == 1) b result = numerator + ""; b else b result = numerator + "/" + denominator; b return result; }
45
Rational.java (cont.) b // Reduces this rational number by dividing both the numerator b // and the denominator by their greatest common divisor. b private void reduce () b { b if (numerator != 0) b { b int common = gcd (Math.abs(numerator), denominator); b numerator = numerator / common; b denominator = denominator / common; b } b // Computes and returns the greatest common divisor of the two b // positive parameters. Uses Euclid's algorithm. b private int gcd (int num1, int num2) b { b while (num1 != num2) b if (num1 > num2) b num1 = num1 - num2; b else b num2 = num2 - num1; b return num1; b } }
46
RationalNumbers.java b //******************************************************************** b // RationalNumbers.java Author: Lewis and Loftus b // Driver to exercise the use of multiple Rational objects. b //******************************************************************** b import Rational; b public class RationalNumbers b { b // Creates some rational number objects and performs various b // operations on them. b public static void main (String[] args) b { b Rational r1 = new Rational (6, 8); b Rational r2 = new Rational (1, 3); b System.out.println ("First rational number: " + r1); b System.out.println ("Second rational number: " + r2);
47
RationalNumbers.java (cont.) b if (r1.equals(r2)) b System.out.println ("r1 and r2 are equal."); b else b System.out.println ("r1 and r2 are NOT equal."); b Rational r3 = r1.add(r2); b Rational r4 = r1.subtract(r2); b Rational r5 = r1.multiply(r2); b Rational r6 = r1.divide(r2); b System.out.println ("r1 + r2: " + r3); b System.out.println ("r1 - r2: " + r4); b System.out.println ("r1 * r2: " + r5); b System.out.println ("r1 / r2: " + r6); b }
48
48 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
49
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
50
50 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);
51
51 Overloading Methods b Constructors can be overloaded b An overloaded constructor provides multiple ways to set up a new object b See Die.java (page 204) Die.java b See SnakeEyes.java (page 203) SnakeEyes.java
52
Die.java b //******************************************************************** b // Die.java Author: Lewis and Loftus b // Represents one die (singular of dice) with faces showing values b // between 1 and the number of faces on the die. b //******************************************************************** b public class Die b { b private final int MIN_FACES = 4; b b private int numFaces; // number of sides on the die b private int faceValue; // current value showing on the die b b // Defaults to a six-sided die, initially showing 1. b public Die () b { b numFaces = 6; b faceValue = 1; b }
53
Die.java (cont.) b // Explicitly sets the size of the die. Defaults to a size of b // six if the parameter is invalid. Initial face is 1. b public Die (int faces) b { b if (faces < MIN_FACES) b numFaces = 6; b else b numFaces = faces; b faceValue = 1; b } b // Rolls the die and returns the result. b public int roll () b { b faceValue = (int) (Math.random() * numFaces) + 1; b return faceValue; b } b // Returns the current die value. b public int getFaceValue () b { b return faceValue; } }
54
SnakeEyes.java b //******************************************************************** b // SnakeEyes.java Author: Lewis and Loftus b // Demonstrates the use of a class with overloaded constructors. b //******************************************************************** b import Die; b public class SnakeEyes b { // Creates two die objects, then rolls both dice a set number of b // times, counting the number of snake eyes that occur. b public static void main (String[] args) b { final int ROLLS = 500; b int snakeEyes = 0, num1, num2; b Die die1 = new Die(); // creates a six-sided die b Die die2 = new Die(20); // creates a twenty-sided die b for (int roll = 1; roll <= ROLLS; roll++) b { num1 = die1.roll(); b num2 = die2.roll(); b if (num1 == 1 && num2 == 1) // check for snake eyes b snakeEyes++; b } b System.out.println ("Number of rolls: " + ROLLS); b System.out.println ("Number of snake eyes: " + snakeEyes); b System.out.println ("Ratio: " + (float)snakeEyes/ROLLS); } }
55
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
56
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 PigLatinTranslator.java (page 208) PigLatinTranslator.java b See PigLatin.java (page 207) PigLatin.java
57
PigLatinTranslator.java b b //******************************************************************** b b // PigLatinTranslator.java Author: Lewis and Loftus b b // Represents a translation system from English to Pig Latin. b b // Demonstrates method decomposition and the use of StringTokenizer. b b //******************************************************************** b b import java.util.StringTokenizer; b b public class PigLatinTranslator bb{bb{ b b // Translates a sentence of words into Pig Latin. b b public String translate (String sentence) b b { b b String result = ""; b b sentence = sentence.toLowerCase(); b b StringTokenizer tokenizer = new StringTokenizer (sentence); bb bb b b while (tokenizer.hasMoreTokens()) b b { b b result += translateWord (tokenizer.nextToken()); b b result += " "; b b } b b return result; }
58
PigLatinTranslator.java (cont.) b // Translates one word into Pig Latin. If the word begins with a vowel, the suffix "yay“ b // is appended to the word. Otherwise, the first letter or two are moved to the end of b // the word, and "ay" is appended. b private String translateWord (String word) b { b String result = ""; b if (beginsWithVowel(word)) b result = word + "yay"; b else b if (beginsWithPrefix(word)) b result = word.substring(2) + word.substring(0,2) + "ay"; b else b result = word.substring(1) + word.charAt(0) + "ay"; b return result; b } b // Determines if the specified word begins with a vowel. b private boolean beginsWithVowel (String word) b { b String vowels = "aeiouAEIOU"; b char letter = word.charAt(0); b return (vowels.indexOf(letter) != -1); }
59
PigLatinTranslator.java (cont.) b // Determines if the specified word begins with a particular two-character prefix. b private boolean beginsWithPrefix (String str) b { b return ( str.startsWith ("bl") || str.startsWith ("pl") || b str.startsWith ("br") || str.startsWith ("pr") || b str.startsWith ("ch") || str.startsWith ("sh") || b str.startsWith ("cl") || str.startsWith ("sl") || b str.startsWith ("cr") || str.startsWith ("sp") || b str.startsWith ("dr") || str.startsWith ("sr") || b str.startsWith ("fl") || str.startsWith ("st") || b str.startsWith ("fr") || str.startsWith ("th") || b str.startsWith ("gl") || str.startsWith ("tr") || b str.startsWith ("gr") || str.startsWith ("wh") || b str.startsWith ("kl") || str.startsWith ("wr") || b str.startsWith ("ph") ); b }
60
PigLatin.java b //****************************************************************** b // PigLatin.java Author: Lewis and Loftus b // Driver to exercise the PigLatinTranslator class. b //****************************************************************** b import PigLatinTranslator; b import cs1.Keyboard; b public class PigLatin b { b // Reads sentences and translates them into Pig Latin. b public static void main (String[] args) b { b String sentence, result, another; b PigLatinTranslator translator = new PigLatinTranslator();
61
PigLatin.java (cont.) b do b { b System.out.println (); b System.out.println ("Enter a sentence (no punctuation):"); b sentence = Keyboard.readString(); b System.out.println (); b result = translator.translate (sentence); b System.out.println ("That sentence in Pig Latin is:"); b System.out.println (result); b System.out.println (); b System.out.print ("Translate another sentence (y/n)? "); b another = Keyboard.readString(); b } b while (another.equalsIgnoreCase("y")); b }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.