Presentation is loading. Please wait.

Presentation is loading. Please wait.

Class Variables and Methods

Similar presentations


Presentation on theme: "Class Variables and Methods"— Presentation transcript:

1 Class Variables and Methods
Chapter 7 Class Variables and Methods Copyright © 2000 W. W. Norton & Company. All rights reserved.

2 7.1 Class Methods Versus Instance Methods
Review from Chapter 3: A Java program consists of classes. Most classes contain both instance variables and instance methods. Any object created from a class will have its own copy of the class’s instance variables, and that object will be capable of calling the class’s (public) instance methods. Examples of classes: Account String (part of the Java API) Copyright © 2000 W. W. Norton & Company. All rights reserved.

3 Instance Method Review
An instance method may access the instance variables in an object without changing them, or it may modify instance variables. If acct is an Account variable, the call acct.deposit( ); deposits $1000 into the Account object that acct represents. If str contains a String object, the length method can be used to find the length of the string: int len = str.length(); Copyright © 2000 W. W. Norton & Company. All rights reserved.

4 Class Methods Not all methods require access to instance variables.
For example, a method that computes the square root of a number has nothing to do with objects. Methods that don’t need access to instance variables are known as class methods (or static methods.) A class method—like all methods in Java—must belong to a class. Copyright © 2000 W. W. Norton & Company. All rights reserved.

5 Class Methods If a class method has been declared public, it can be called as follows: class . method-name ( arguments ) When a class method is called by another method in the same class, the class name and dot can be omitted. Copyright © 2000 W. W. Norton & Company. All rights reserved.

6 Class Methods Class methods used in Chapter 2: SimpleIO.prompt
SimpleIO.readLine Convert.toDouble Integer.parseInt Math.abs Math.max Math.min Math.pow Math.round Math.sqrt Copyright © 2000 W. W. Norton & Company. All rights reserved.

7 Class Methods Uses of class methods:
To provide a service to other classes. Methods in this category are declared public. To help other methods in the same class. “Helper” methods provide assistance to other methods in the same class. Helper methods should be private. To provide access to hidden class variables. If a class variable is private, the only way for a method in a different class to access the variable or to change its value is to call a class method that has permission to access the variable. Methods in this category are declared public. Copyright © 2000 W. W. Norton & Company. All rights reserved.

8 Class Methods Class methods have another important purpose: to specify where a program begins execution. Every Java application must have a main method. main is a class method, so every Java application has at least one class method. Many classes in the Java API provide class methods, including Math, System, and String. Copyright © 2000 W. W. Norton & Company. All rights reserved.

9 Example: The Math Class
The Math class contains no instance variables and no instance methods; it’s just a repository for math functions (class methods) and math constants. Since Math has no instance variables, so there’s no point in creating instances of this class. A class from which objects can be created is said to be instantiable. The Math class is not instantiable. Copyright © 2000 W. W. Norton & Company. All rights reserved.

10 Example: The System Class
The System class contains a number of class methods, including exit, which causes program termination. A call of System.exit: System.exit(0); The argument (an int value) is a status code that can be tested after program termination. By convention, 0 indicates normal termination. Any other value (such as –1) indicates abnormal termination. Copyright © 2000 W. W. Norton & Company. All rights reserved.

11 Example: The System Class
Calling System.exit is a more drastic way to terminate a program than simply returning from main. If a program displays a frame on the screen, the program won’t terminate until the frame is closed, even if main has completed execution. On the other hand, calling System.exit causes immediate program termination; any frames that are visible on the screen will be closed. The System class is not instantiable. Copyright © 2000 W. W. Norton & Company. All rights reserved.

12 Example: The String Class
Java’s String class contains several overloaded class methods named valueOf that convert different types of data to string form. Examples: String intString = String.valueOf(607); String doubleString = String.valueOf(4.5); The value of intString will be "607" and the value of doubleString will be "4.5". String is an example of a class that contains both instance methods and class methods. Copyright © 2000 W. W. Norton & Company. All rights reserved.

13 Summary Instance Methods Perform an operation on an object.
Are called by an object. Have access to instance variables inside the calling object. Class Methods Do not perform an operation on an object. Are not called by an object. Do not have access to instance variables. Copyright © 2000 W. W. Norton & Company. All rights reserved.

14 7.2 Writing Class Methods Writing a class method is similar to writing an instance method, except that the declaration of a class method must contain the word static. Parts of a class method declaration: Access modifier The word static Result type Method name Parameters Body Copyright © 2000 W. W. Norton & Company. All rights reserved.

15 Declaring Class Methods
Example of a class method declaration: Copyright © 2000 W. W. Norton & Company. All rights reserved.

16 Parameters for Class Methods
Java requires that main’s result type be void and that main have one parameter of type String[] (array of String objects). Other class methods may have any number of parameters, including none. If a method has more than one parameter, each parameter except the last must be followed by a comma. Copyright © 2000 W. W. Norton & Company. All rights reserved.

17 Access Modifiers for Class Methods
Java requires that the main method be declared public. Other class methods can be declared either public or private. Class methods that are intended for use by other classes should be declared public. Class methods that are intended for use within a single class should be declared private. A private method can be modified without having to worry about how the changes might affect other classes. Copyright © 2000 W. W. Norton & Company. All rights reserved.

18 Example: A Termination Method
When a program encounters an error condition, it may need to notify the user and terminate. The following two statements accomplish this task: System.out.println("Invalid input; consult manual."); System.exit(-1); // Terminate abnormally Because these statements might appear many times in a program, with only minor changes (different messages to the user), it makes sense to put them into a class method. Copyright © 2000 W. W. Norton & Company. All rights reserved.

19 Example: A Termination Method
A declaration of the class method: private static void terminate(String message) { System.out.println(message); System.exit(-1); // Terminate abnormally } A call of terminate: terminate("Invalid input; consult manual."); Because this call will be in the same class as the method itself, there’s no need to mention the class name in the call. Copyright © 2000 W. W. Norton & Company. All rights reserved.

20 Local Variables The body of any class or instance method may contain declarations of local variables. Properties of local variables: A local variable can be accessed only within the method that contains its declaration. When a method returns, its local variables no longer exist, so their values are lost. A method is not allowed to access the value stored in a local variable until the variable has been initialized. A local variable can be declared final to indicate that its value doesn’t change after initialization. Copyright © 2000 W. W. Norton & Company. All rights reserved.

21 7.3 The return Statement When a method has a result type other than void, a return statement must be used to specify what value the method returns. Form of the return statement: return expression ; The expression is often just a literal or a variable: return 0; return n; Expressions containing operators are also allowed: return x * x - 2 * x + 1; Copyright © 2000 W. W. Norton & Company. All rights reserved.

22 Using Variables in return Statements
A class method that computes the value of the polynomial x2 – 2x + 1: private static double poly(double x) { return x * x - 2 * x + 1; } A local variable could be used to store the return value: double y = x * x - 2 * x + 1; return y; It’s usually best to avoid variables that are assigned a value only once. Copyright © 2000 W. W. Norton & Company. All rights reserved.

23 A Common Error When a method returns a result, make sure that there’s no way to leave the method without executing a return statement. The following method body is illegal, because the method returns nothing if n is equal to 0: if (n > 0) return +1; else if (n < 0) return -1; Copyright © 2000 W. W. Norton & Company. All rights reserved.

24 return Statements in void Methods
return statements can be used in methods whose result type is void. The expression after the word return must be omitted: return; A return statement of this form allows a method to return before it has executed all the statements in its body. Copyright © 2000 W. W. Norton & Company. All rights reserved.

25 Example: A Dollar-Formatting Method
In the U.S., monetary amounts are normally displayed in the form dollars.cents, where cents is a two-digit number between 00 and 99. If a double variable is used to store a dollar amount, System.out.print and System.out.println won’t always provide the desired formatting: will display as 10.5 and will be printed as 1.0E7. Also, amounts won’t be rounded to cents, so values such as may be printed. Copyright © 2000 W. W. Norton & Company. All rights reserved.

26 Example: A Dollar-Formatting Method
The Java API provides methods for formatting numbers, but it’s easy to write such a method. A possible strategy for converting a dollar amount to a string that’s suitable for printing: 1. Multiply the amount by 100 and round to the nearest integer (call this roundedAmount). 2. Determine the number of dollars (roundedAmount divided by 100) and the number of cents (the remainder when roundedAmount is divided by 100). 3. Build a string consisting of the number of dollars, a period, and the number of cents. If the number of cents is a single-digit number, put a zero between the period and the number of cents. Copyright © 2000 W. W. Norton & Company. All rights reserved.

27 Example: A Dollar-Formatting Method
A class method that implements this strategy: private static String formatAsMoney(double amount) { long roundedAmount = Math.round(amount * 100); long dollars = roundedAmount / 100; long cents = roundedAmount % 100; String result; if (cents <= 9) result = dollars + ".0" + cents; else result = dollars + "." + cents; return result; } Math.round returns a long value. long is similar to int but allows numbers to be larger. Copyright © 2000 W. W. Norton & Company. All rights reserved.

28 Example: A Dollar-Formatting Method
formatAsMoney can be simplified by replacing the if statement and the return statement with the following statement: if (cents <= 9) return dollars + ".0" + cents; else return dollars + "." + cents; Once this change has been made, the declaration of result can be removed. Copyright © 2000 W. W. Norton & Company. All rights reserved.

29 Example: A Dollar-Formatting Method
An example of calling formatAsMoney: String formattedAmount = formatAsMoney(dollarAmount); dollarAmount is a double variable. The value returned by formatAsMoney can be used without first storing it in a variable: System.out.println( "$" + formatAsMoney(dollarAmount)); Copyright © 2000 W. W. Norton & Company. All rights reserved.

30 Conditional Expressions
The two return statements in the formatAsMoney method are nearly identical: if (cents <= 9) return dollars + ".0" + cents; else return dollars + "." + cents; This suggests that there might be a way to simplify the code. Java’s conditional operator is often handy in such situations. Copyright © 2000 W. W. Norton & Company. All rights reserved.

31 Conditional Expressions
The conditional operator is similar to the if statement: it tests a condition and performs one of two actions, depending on the outcome of the test. Unlike the if statement, the conditional operator produces a value. This property gives the conditional operator greater flexibility than the if statement. Copyright © 2000 W. W. Norton & Company. All rights reserved.

32 Conditional Expressions
The conditional operator consists of the symbols ? and :, which must be used together: expr1 ? expr2 : expr3 expr1 must be a boolean expression; expr2 and expr3 are normally expressions of the same type. The resulting expression is said to be a conditional expression. The conditional operator is a ternary operator, because it requires three operands instead of one or two. Copyright © 2000 W. W. Norton & Company. All rights reserved.

33 Conditional Expressions
The conditional expression expr1 ? expr2 : expr3 should be read “if expr1 then expr2 else expr3.” A conditional expression is evaluated in stages: expr1 is evaluated first. If the value of expr1 is true, then expr2 is evaluated, and its value is the value of the entire conditional. If the value of expr1 is false, then the value of expr3 is the value of the entire conditional. Copyright © 2000 W. W. Norton & Company. All rights reserved.

34 Conditional Expressions
The if statement in the formatAsMoney method can be replaced by a return statement: return (cents <= 9) ? (dollars + ".0" + cents) : (dollars + "." + cents); The return statement can be condensed further: return dollars + (cents <= 9 ? ".0" : ".") + cents; The parentheses in the second example are mandatory. The conditional operator has lower precedence than all other operators except the assignment operators. Copyright © 2000 W. W. Norton & Company. All rights reserved.

35 Conditional Expressions
The conditional operator isn’t used much in Java except in return statements. Conditional expressions occasionally appear in calls of System.out.print or System.out.println. The statement if (isLeapYear) System.out.println("February has 29 days"); else System.out.println("February has 28 days"); could be written as System.out.println("February has " + (isLeapYear ? 29 : 28) + " days"); Copyright © 2000 W. W. Norton & Company. All rights reserved.

36 Conditional Expressions
A conditional expression can be used just like any other kind of expression. For example, a conditional expression can appear on the right side of an assignment: int i = 1; int j = 2; int m = i > j ? i : j; // m is 2 int n = (i >= 0 ? i : 0) + j; // n is 3 Copyright © 2000 W. W. Norton & Company. All rights reserved.

37 7.4 Parameters A method is allowed to have parameters, which represent values that will be supplied when the method is called. The values actually supplied to the method at the time of the call are said to be arguments. The issues that arise when parameters are used are relevant to both instance methods and class methods. Copyright © 2000 W. W. Norton & Company. All rights reserved.

38 How Arguments Are Passed
When a method is called, it is supplied with copies of the arguments that appear in the method call. The arguments are passed by value, because the value of each argument is given to the called method. The meaning of “copy” depends on the type of the argument. An object variable contains a reference to an object, not the object itself. For this reason, classes are said to be reference types. (Array types are also reference types.) All other types are said to be primitive types. Copyright © 2000 W. W. Norton & Company. All rights reserved.

39 How Arguments Are Passed
The effect of passing an argument to a method: Primitive type. The value of the argument is copied into the corresponding parameter. Reference type. The value of the argument—a reference—is copied into the parameter. Assigning a new value to a parameter is legal but has no effect on the corresponding argument. If the parameter refers to an object, then changes made to that object—for example, by calling a method that modifies the object—will be reflected in the argument. Copyright © 2000 W. W. Norton & Company. All rights reserved.

40 How Arguments Are Passed
Example 1: Assigning a new value to a parameter. The following class method writes a line consisting of stars (asterisks): private static void printStars(int numStars) { while (numStars-- > 0) System.out.print('*'); System.out.println(); } Copyright © 2000 W. W. Norton & Company. All rights reserved.

41 How Arguments Are Passed
An example in which printStars is called: int n = 30; System.out.println("Value of n before call: " + n); printStars(n); System.out.println("Value of n after call: " + n); The output produced by these statements: Value of n before call: 30 ****************************** Value of n after call: 30 Copyright © 2000 W. W. Norton & Company. All rights reserved.

42 How Arguments Are Passed
When printStars was called, the value of n was copied into the numStars parameter: Copyright © 2000 W. W. Norton & Company. All rights reserved.

43 How Arguments Are Passed
Because numStars was a copy of n, decrementing numStars didn’t change n. At the end of the method call, n and numStars have the following appearance: Copyright © 2000 W. W. Norton & Company. All rights reserved.

44 How Arguments Are Passed
Example 2: Modifying an object passed as an argument. A method that transfers the balance in oldAccount to newAccount, then closes oldAccount: private static void transferBalance( Account oldAccount, Account newAccount) { newAccount.deposit(oldAccount.getBalance()); oldAccount.close(); } Copyright © 2000 W. W. Norton & Company. All rights reserved.

45 How Arguments Are Passed
The calls of deposit and close don’t change the values of oldAccount and newAccount. They do, however, change the state of the objects that oldAccount and newAccount represent. To see how transferBalance works, assume that acct1 and acct2 are declared as follows: Account acct1 = new Account( ); Account acct2 = new Account(500.00); Copyright © 2000 W. W. Norton & Company. All rights reserved.

46 How Arguments Are Passed
A visual representation of acct1 and acct2: Copyright © 2000 W. W. Norton & Company. All rights reserved.

47 How Arguments Are Passed
Now suppose that the following statement is executed: transferBalance(acct1, acct2); As the method begins to execute, acct1 is copied into oldAccount, and acct2 is copied into newAccount. Copyright © 2000 W. W. Norton & Company. All rights reserved.

48 How Arguments Are Passed
oldAccount now refers to the same object as acct1, and newAccount refers to the same object as acct2: Copyright © 2000 W. W. Norton & Company. All rights reserved.

49 How Arguments Are Passed
The transferBalance method executes the call oldAccount.getBalance(), which returns Next, this value is added to the balance stored in the newAccount object, causing its balance to increase to Finally, oldAccount.close() is executed, causing the balance in the oldAccount object to be set to zero. Copyright © 2000 W. W. Norton & Company. All rights reserved.

50 How Arguments Are Passed
As a result of calling transferBalance, the state of the acct1 and acct2 objects is changed: Copyright © 2000 W. W. Norton & Company. All rights reserved.

51 Array Parameters Passing arrays to methods is much like passing objects. A method that searches an array of strings to see if it contains a particular string (the search key): private static int findString(String[] strings, String key) { for (int i = 0; i < strings.length; i++) if (strings[i].equals(key)) return i; return -1; } If it finds the key in the array, findString returns the key’s position. If findString fails to find the key, it returns –1. Copyright © 2000 W. W. Norton & Company. All rights reserved.

52 Array Parameters When an array is passed to a method, only a reference to the array is copied. As a result, passing an array to a method takes very little time. Also, a method can modify the elements of any array passed to it. For example, the following method will assign zero to the elements of an array passed to it: private static void setElementsToZero(int[] a) { for (int i = 0; i < a.length; i++) a[i] = 0; } Copyright © 2000 W. W. Norton & Company. All rights reserved.

53 Program Arguments In many operating systems, the user can launch programs from a command line. The Java compiler itself is launched from the command line: javac MyProgram.java javac obtains the name of the .java file from the command line. When a program is launched from the command line, it can access information (file names, for example) entered as part of the command. Copyright © 2000 W. W. Norton & Company. All rights reserved.

54 Program Arguments Some programs have switches or options that can be specified on the command line to affect the program’s behavior. These usually begin with a distinctive character, such as - or /. javac has a -O option, which causes it to “optimize” a program for better performance: javac -O MyProgram.java Copyright © 2000 W. W. Norton & Company. All rights reserved.

55 Program Arguments The term program arguments (or command-line arguments) refers to any data supplied by the user on the command line (not including the name of the program itself). Command-line arguments don’t have to be options or file names, although in practice they usually are. Copyright © 2000 W. W. Norton & Company. All rights reserved.

56 Program Arguments It’s easy to write a program that accesses command-line arguments supplied by the user. The main method is required to have a single parameter, which is customarily named args: public static void main(String[] args) { } When the program is executed, args will contain the program’s command-line arguments. Copyright © 2000 W. W. Norton & Company. All rights reserved.

57 Program Arguments Suppose that CopyFile is a Java program that’s been launched using the following command: java CopyFile MyProgram.java MyProgram2.java Inside CopyFile’s main method, the args array will contain the following values: args[0]  "MyProgram.java" args[1]  "MyProgram2.java" Copyright © 2000 W. W. Norton & Company. All rights reserved.

58 Program Arguments The main method’s parameter doesn’t have to be named args ( “arguments”). argv—“argument vector”—is also popular. The square brackets can go after args if desired: public static void main(String args[]) { } Typically, a program will use a loop to examine and process the command-line arguments. Copyright © 2000 W. W. Norton & Company. All rights reserved.

59 Program: Printing Command-Line Arguments
A program that prints each command-line argument on a line by itself: PrintArgs.java // Prints command-line arguments on separate lines public class PrintArgs { public static void main(String[] args) { for (int i = 0; i < args.length; i++) System.out.println(args[i]); } Copyright © 2000 W. W. Norton & Company. All rights reserved.

60 Program: Printing Command-Line Arguments
Suppose that PrintArgs is executed using the following command: java PrintArgs Java rules The output of PrintArgs: Java rules Copyright © 2000 W. W. Norton & Company. All rights reserved.

61 7.5 Class Variables Objects store their state in instance variables. Every object has its own set of these variables. Variables that belong to a class, but not to any particular instance of a class, are called class variables. Some books use the terms static variables or static fields instead. Class variables are stored only once in the entire program. Copyright © 2000 W. W. Norton & Company. All rights reserved.

62 Declaring Class Variables
In declarations of class variables, the word static is inserted between the access modifier and the type of the variable: public static int numAccounts; private static int windowHeight; Variables that are declared public are accessible outside the class. Variables that are declared private are hidden inside the class. Copyright © 2000 W. W. Norton & Company. All rights reserved.

63 Using Class Variables A public class variable can be accessed by writing the name of the class, a dot, and the name of the variable. If the numAccounts is declared in a class named Account, the following statement is legal: int accountsOpen = Account.numAccounts; Within the class in which it’s declared, a class variable can be accessed directly, without a class name or dot: numAccounts++; A private class variable can be accessed only within its own class, so the class name and dot aren’t needed: windowHeight = 200; Copyright © 2000 W. W. Norton & Company. All rights reserved.

64 Uses for Class Variables
Common uses for class variables: As global variables. (A global variable is a variable that can be used by any method in any class.) As constants. To store data for class methods. Class variables can also be used by instance methods. Copyright © 2000 W. W. Norton & Company. All rights reserved.

65 Using Class Variables as Global Variables
In Java, there’s no way to declare a variable that exists “outside” the classes in a program. Instead, a variable that must be universally available is put into a class and declared to be a public class variable. Global variables make programs harder to test and harder to modify, so it’s usually best to avoid them. Copyright © 2000 W. W. Norton & Company. All rights reserved.

66 Class Variables in the System Class
Every call of System.out.print or System.out.println involves a global variable. The System class has three class variables: in, out, and err. These variables are all public, which means that they can be accessed by writing System.in, System.out, and System.err. Each variable represents a stream—a source of input or a destination for output. Copyright © 2000 W. W. Norton & Company. All rights reserved.

67 Class Variables in the System Class
System.in represents the standard input stream. By default, the standard input stream is attached to the user’s keyboard. System.out represents the standard output stream. By default, data written to System.out is displayed in the window in the program was launched. System.err represents the standard error stream, which is a convenient place to write error messages. By default, data written to System.err is displayed in the same window as data written to System.out. Copyright © 2000 W. W. Norton & Company. All rights reserved.

68 Redirecting the Standard Streams
Operating systems often allow the user to redirect the standard streams. In Windows or Unix, the standard input stream can be redirected so that data comes from a file instead of from the keyboard: java MyProgram <myInputFile The output of a program can also be sent to a file: java MyProgram >myOutputFile myOutputFile will be created if it doesn’t exist. Copyright © 2000 W. W. Norton & Company. All rights reserved.

69 Redirecting the Standard Streams
A program can read from one file and write to another: java MyProgram <myInputFile >myOutputFile If the user redirects the program’s output, error messages written to System.out won’t appear on the screen. Error messages written to System.err will still appear on the screen, because redirecting System.out has no effect on System.err. Writing to System.err is similar to writing to System.out: System.err.println("Invalid data encountered"); Copyright © 2000 W. W. Norton & Company. All rights reserved.

70 The PrintStream Class System.out and System.err are instances of the PrintStream class, which provides the print and println methods. Consider a typical call of System.out.println: System.out.println("Java rules!"); System.out is a class variable that represents an instance of the PrintStream class. This object is invoking println, one of the instance methods in the PrintStream class. Copyright © 2000 W. W. Norton & Company. All rights reserved.

71 Using Class Variables as Constants
Including the word final in the declaration of a class variable makes it a constant. Java’s Math class contains two final class variables: public class Math { public static final double E = ; public static final double PI = ; } E and PI are accessed by writing Math.E and Math.PI. Copyright © 2000 W. W. Norton & Company. All rights reserved.

72 Using Class Variables as Constants
Other examples of class variables used as constants: Color.white, Color.black, ... Font.PLAIN, Font.BOLD, Font.ITALIC Most API classes follow the convention of using all uppercase letters for names of constants. Like all class variables, constants can be declared public or private. Constants that are to be used by other classes must be declared public. Copyright © 2000 W. W. Norton & Company. All rights reserved.

73 Using Class Variables to Store Data for Class Methods
When a method returns, its local variables no longer exist. If a class method needs to store data where it will be safe after the method returns, it must use a class variable instead of a local variable. Class variables are also used for sharing data among class methods in a class. Class variables that store data for class methods should be declared private. Copyright © 2000 W. W. Norton & Company. All rights reserved.

74 Summary Instance Variables Declared in a class.
Created when an instance of the class is created. Retain values as long as object exists. Access controlled by public and private. Class Variables Declared in a class. Created when program begins to execute. Retain values until program terminates. Access controlled by public and private. Local Variables Declared in a method. Created when method is called. Retain values until method returns. Access limited to method in which declared. Copyright © 2000 W. W. Norton & Company. All rights reserved.

75 7.6 Adding Class Variables and Methods to a Class
The outline of a program that contains class variables and class methods, in addition to main: public class class-name { declarations of class variables public static void main(String[] args) { } declarations of class methods Java doesn’t require that class variables and methods go in any particular order. Copyright © 2000 W. W. Norton & Company. All rights reserved.

76 Example: Modifying the DisplayText Program
The DisplayText program could benefit from the addition of class variables and methods. The original program: // Displays text in three different colors and styles import java.awt.*; import jpb.*; public class DisplayText { public static void main(String[] args) { // Create drawable frame DrawableFrame df = new DrawableFrame("Display Text"); df.show(); df.setSize(210, 85); // Obtain graphics context Graphics g = df.getGraphicsContext(); Copyright © 2000 W. W. Norton & Company. All rights reserved.

77 Example: Modifying the DisplayText Program
// Display "Monospaced Bold" g.setColor(Color.red); g.setFont(new Font("Monospaced", Font.BOLD, 20)); g.drawString("Monospaced Bold", 15, 25); // Display "SansSerif Italic" g.setColor(Color.green); g.setFont(new Font("SansSerif", Font.ITALIC, 20)); g.drawString("SansSerif Italic", 15, 50); // Display "Serif Plain" g.setColor(Color.blue); g.setFont(new Font("Serif", Font.PLAIN, 20)); g.drawString("Serif Plain", 15, 75); // Repaint frame df.repaint(); } Copyright © 2000 W. W. Norton & Company. All rights reserved.

78 Example: Modifying the DisplayText Program
A method named displayFont could perform the setColor/setFont/drawString steps. The differences in the steps are the drawing color, the font name and style, the string to be displayed, and the y coordinate of the string’s baseline. These will need to be parameters to displayFont. The steps don’t change any of the program’s variables, so displayFont won’t need to return a result. Copyright © 2000 W. W. Norton & Company. All rights reserved.

79 Example: Modifying the DisplayText Program
The displayFont method: private static void displayFont(Color c, String fontName, int fontStyle, String message, int y) { g.setColor(c); g.setFont(new Font(fontName, fontStyle, 20)); g.drawString(message, 15, y); } There’s one problem: displayFont uses the variable g, which is declared in main. Either displayFont will need a Graphics parameter, or g will need to be a class variable. Copyright © 2000 W. W. Norton & Company. All rights reserved.

80 DisplayText2.java // Displays text in three different colors and styles import java.awt.*; import jpb.*; public class DisplayText2 { private static Graphics g; // Class variable public static void main(String[] args) { // Create drawable frame DrawableFrame df = new DrawableFrame("Display Text"); df.show(); df.setSize(210, 85); // Obtain graphics context g = df.getGraphicsContext(); // Display "Monospaced Bold" displayFont(Color.red, "Monospaced", Font.BOLD, "Monospaced Bold", 25); Copyright © 2000 W. W. Norton & Company. All rights reserved.

81 // Display "SansSerif Italic"
displayFont(Color.green, "SansSerif", Font.ITALIC, "SansSerif Italic", 50); // Display "Serif Plain" displayFont(Color.blue, "Serif", Font.PLAIN, "Serif Plain", 75); // Repaint frame df.repaint(); } private static void displayFont(Color c, String fontName, int fontStyle, String message, int y) { g.setColor(c); g.setFont(new Font(fontName, fontStyle, 20)); g.drawString(message, 15, y); Copyright © 2000 W. W. Norton & Company. All rights reserved.

82 7.7 Writing Helper Methods
Instead of putting all the code for a program into main, it’s better to delegate some of its duties to helper methods. In general, a helper method is any method whose job is to assist another method, not necessarily main. A helper for a class method such as main must be another class method, because class methods aren't allowed to call instance methods in the same class. Instance methods can have helpers as well. A helper for an instance method can be either an instance method or a class method. Copyright © 2000 W. W. Norton & Company. All rights reserved.

83 Advantages of Using Helper Methods
Helper methods have two primary advantages: Greater clarity. The main method can be shortened, with helper methods taking care of details. Less redundancy. A repeated segment of code can be moved into a method and then called as many times as needed. The CourseAverage program of Section 2.11 suffers from a great deal of repetitive code. By moving this code to class methods, the program can be made shorter, as well as more understandable and easier to modify. Copyright © 2000 W. W. Norton & Company. All rights reserved.

84 Improving Clarity The original design of CourseAverage:
1. Print the introductory message (“Welcome to the CSc 2310 average calculation program”). 2. Prompt the user to enter eight program scores. 3. Compute the program average from the eight scores. 4. Prompt the user to enter five quiz scores. 5. Compute the quiz average from the five scores. 6. Prompt the user to enter scores on the tests and final exam. 7. Compute the course average from the program average, quiz average, test scores, and final exam score. 8. Round the course average to the nearest integer and display it. Copyright © 2000 W. W. Norton & Company. All rights reserved.

85 Improving Clarity Most of the steps are fairly small, with the exception of steps 2 and 4. Helper methods that perform these steps will improve the program’s clarity. Both methods will return a double value: private static double readProgramScores() { } private static double readQuizScores() { Copyright © 2000 W. W. Norton & Company. All rights reserved.

86 Reducing Redundancy readProgramScores will consist of eight steps (one for each program score). Each step involves prompting the user to enter a number, reading the number as a string, and then converting the string to numeric form. Because the eight steps are nearly identical, it makes sense to write a helper method (readDouble) that performs a single prompt/read/convert step. readDouble can also be used to help write readQuizScores. Copyright © 2000 W. W. Norton & Company. All rights reserved.

87 Reducing Redundancy In the original CourseAverage program, a single prompt/read/convert step consists of statements such as the following: SimpleIO.prompt("Enter Program 1 score: "); String userInput = SimpleIO.readLine(); double program1 = Convert.toDouble(userInput); Since the prompt is different each time, it will need to be a parameter to readDouble. readDouble will need to return the value entered by the user, after it has been converted to double form. Copyright © 2000 W. W. Norton & Company. All rights reserved.

88 Reducing Redundancy The three statements in the prompt/read/convert step will be replaced by a single method call: program1 = readDouble("Enter Program 1 score: "); The readDouble method: private static double readDouble(String prompt) { SimpleIO.prompt(prompt); String userInput = SimpleIO.readLine(); return Convert.toDouble(userInput); } Copyright © 2000 W. W. Norton & Company. All rights reserved.

89 The Revised CourseAverage Program
The revised CourseAverage program has three class methods: readProgramScores, readQuizScores, and readDouble. Other changes to the program: Class variables are used as constants. Loops are used to read the program scores and grades. The readDouble method is used to help read the test scores and the final exam score. Copyright © 2000 W. W. Norton & Company. All rights reserved.

90 CourseAverage2.java // Program name: CourseAverage2
// Author: K. N. King // Written: // Modified: // // Prompts the user to enter eight program scores (0-20), five // quiz scores (0-10), two test scores (0-100), and a final // exam score (0-100). Scores may contain digits after the // decimal point. Input is not checked for validity. Displays // the course average, computed using the following formula: // Programs 30% // Quizzes % // Test % // Test % // Final exam 30% // The course average is rounded to the nearest integer. Copyright © 2000 W. W. Norton & Company. All rights reserved.

91 public class CourseAverage2 { // Constants
import jpb.*; public class CourseAverage2 { // Constants private static final int NUM_PROGRAMS = 8; private static final int NUM_QUIZZES = 5; private static final int MAX_PROG_SCORE = 20; private static final int MAX_QUIZ_SCORE = 10; private static final double PROGRAM_WEIGHT = .30; private static final double QUIZ_WEIGHT = .10; private static final double TEST_WEIGHT = .15; private static final double FINAL_EXAM_WEIGHT = .30; public static void main(String[] args) { // Print the introductory message System.out.println("Welcome to the CSc 2310 average " + "calculation program.\n"); Copyright © 2000 W. W. Norton & Company. All rights reserved.

92 // Prompt the user to enter program scores and compute
// the average of the scores double programAverage = readProgramScores() / NUM_PROGRAMS; // Leave a blank line System.out.println(); // Prompt the user to enter quiz scores and compute the // average of the scores double quizAverage = readQuizScores() / NUM_QUIZZES; // Prompt the user to enter scores on the tests and final // exam double test1 = readDouble("Enter Test 1 score: "); double test2 = readDouble("Enter Test 2 score: "); double finalExam = readDouble("Enter Final Exam score: "); Copyright © 2000 W. W. Norton & Company. All rights reserved.

93 // Compute the course average from the program average,
// quiz average, test scores, and final exam score double courseAverage = PROGRAM_WEIGHT * (programAverage / MAX_PROG_SCORE * 100) + QUIZ_WEIGHT * (quizAverage / MAX_QUIZ_SCORE * 100) + TEST_WEIGHT * test1 + TEST_WEIGHT * test2 + FINAL_EXAM_WEIGHT * finalExam; // Round the course average to the nearest integer and // display it System.out.println("\nCourse average: " + Math.round(courseAverage)); } Copyright © 2000 W. W. Norton & Company. All rights reserved.

94 ///////////////////////////////////////////////////////////
// NAME: readProgramScores // BEHAVIOR: Prompts the user to enter program scores // and computes their total. // PARAMETERS: None // RETURNS: Total of program scores private static double readProgramScores() { double programTotal = 0.0; for (int i = 1; i <= NUM_PROGRAMS; i++) programTotal += readDouble("Enter Program " + i + " score: "); return programTotal; } Copyright © 2000 W. W. Norton & Company. All rights reserved.

95 ///////////////////////////////////////////////////////////
// NAME: readQuizScores // BEHAVIOR: Prompts the user to enter quiz scores and // computes their total. // PARAMETERS: None // RETURNS: Total of quiz scores private static double readQuizScores() { double quizTotal = 0.0; for (int i = 1; i <= NUM_QUIZZES; i++) quizTotal += readDouble("Enter Quiz " + i + " score: "); return quizTotal; } Copyright © 2000 W. W. Norton & Company. All rights reserved.

96 ///////////////////////////////////////////////////////////
// NAME: readDouble // BEHAVIOR: Prompts the user to enter a number, reads // the user's input, and converts it to double // form. // PARAMETERS: prompt - the prompt to be displayed // RETURNS: User's input after conversion to double private static double readDouble(String prompt) { SimpleIO.prompt(prompt); String userInput = SimpleIO.readLine(); return Convert.toDouble(userInput); } Copyright © 2000 W. W. Norton & Company. All rights reserved.

97 Comment Blocks for Methods
Each method (except main) should be preceded by a comment block that gives the name of the method and describes what the method does. The comment block should include a description of each parameter and what value (if any) the method returns. The comment block for a method should not describe how the method is used in the program. Copyright © 2000 W. W. Norton & Company. All rights reserved.

98 Reusing Helper Methods
Some helper methods (readProgramScores and readQuizScores, for example) are specific to a particular program. Others, like readDouble, are potentially useful in other programs as well. Section 10.8 shows how to create separate classes for helper methods, making them easier to reuse in other programs. Copyright © 2000 W. W. Norton & Company. All rights reserved.

99 7.8 Designing Methods Issues that arise in the design of methods:
When is a method needed? What should the name of the method be? What parameters will it need? Most of these issues are relevant for instance methods as well. Copyright © 2000 W. W. Norton & Company. All rights reserved.

100 Cohesion A method should perform a single, clearly defined task that can be stated in a sentence or two. A method that performs a single task is said to be cohesive. Copyright © 2000 W. W. Norton & Company. All rights reserved.

101 Stepwise Refinement If a method is too large, often the best thing to do is write helper methods for the method. Dividing larger methods into smaller ones is part of a design strategy known as stepwise refinement or top-down decomposition. If a method will perform the same action two or more times, the code for performing the action should go into a separate method. If an action is performed in just one place, but the action is rather long and complicated, it’s often a good idea to move it to a separate method as well. Copyright © 2000 W. W. Norton & Company. All rights reserved.

102 Stepwise Refinement Ideally, the final program will contain only short methods. Stepwise refinement begins with main. A well-designed main method shouldn’t be very long. main should reveal the program’s top-level design, not get bogged down in details. Stepwise refinement may require more than one iteration. Methods that were spun off from main may need helper methods. Those methods may then need additional helper methods, and so on. Copyright © 2000 W. W. Norton & Company. All rights reserved.

103 Methods by Other Names …
Simplifying a programming task by dividing it into smaller parts is one of the oldest ideas in programming. The first programming book (Preparation of Programs for an Electronic Digital Computer, 1951) was a collection of subroutines. The subroutine concept dates back even further. In 1837, Charles Babbage published a description of a mechanical computer. The Analytical Engine was programmable, using punched cards; the same cards would be used each time a particular calculation needed to be done. Copyright © 2000 W. W. Norton & Company. All rights reserved.

104 Choosing Method Names Choosing method names wisely will have a big impact on program readability. Guidelines for choosing method names: Start with a verb. If the verb isn’t descriptive enough by itself, include a noun. Add adjectives if necessary to clarify the noun. Copyright © 2000 W. W. Norton & Company. All rights reserved.

105 Choosing Method Names Start with a verb. Actions are described by verbs in English, so method names nearly always include a verb. Examples: deposit withdraw readLine terminate formatAsMoney If a method returns a boolean value, the method’s name should begin with a verb such as is or has (for example, isInteger). Copyright © 2000 W. W. Norton & Company. All rights reserved.

106 Choosing Method Names If the verb isn’t descriptive enough by itself, include a noun. In many cases, a noun will need to be included in to indicate the target of the action. Examples: getBalance is better than get readLine is better than read formatAsMoney is better than format Copyright © 2000 W. W. Norton & Company. All rights reserved.

107 Choosing Method Names Add adjectives if necessary to clarify the noun.
convertToDollars isn’t a good method name if there are methods for converting British pounds to U.S. dollars and to Canadian dollars. The names convertToUSDollars and convertToCanadianDollars are better. Copyright © 2000 W. W. Norton & Company. All rights reserved.

108 Choosing Method Names Java’s conventions sometimes deviate slightly from these guidelines. In particular, a method that converts an object to type T is customarily named toT (the verb “convert” is implied). toString is an example of this convention. Copyright © 2000 W. W. Norton & Company. All rights reserved.

109 Parameters Versus Class Variables
Class methods have two ways to obtain any data that they need: through parameters and through class variables. It’s better for a method to obtain data via parameters. A method that relies solely on parameters is self-contained; a method that accesses class variables is not. Class variables are best used to maintain long-term information about the state of a class, rather than being used to supply data to class methods. Copyright © 2000 W. W. Norton & Company. All rights reserved.

110 Parameters Versus Class Variables
However, methods shouldn’t have so many parameters that they become difficult to use. Remembering what the parameters are becomes difficult, as does formatting the method’s declaration and its calls. If methods require an excessive number of parameters, or if the same variable will be needed by most of the methods in a class, class variables should be considered. Copyright © 2000 W. W. Norton & Company. All rights reserved.

111 Return Type Part of designing a method involves deciding whether or not the method returns a value. A method is allowed to return any value, whether it be a value of a primitive type (such as an int value or double value) or an object. Some methods obviously produce a result: getBalance returns the amount of money in an account. readLine returns the line of text that it read. formatAsMoney returns a string containing a dollar amount. Copyright © 2000 W. W. Norton & Company. All rights reserved.

112 Return Type The only other way for a class method to leave data behind is to alter a class variable, which should usually be avoided. It’s easy for someone reading a program to see that a method has returned a value; it’s much more difficult to detect that a method has changed class variables. Copyright © 2000 W. W. Norton & Company. All rights reserved.


Download ppt "Class Variables and Methods"

Similar presentations


Ads by Google