Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 7 Class.

Similar presentations


Presentation on theme: "Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 7 Class."— Presentation transcript:

1 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 7 Class Variables and Methods

2 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 2 7.1Class Methods Versus Instance Methods An instance method can be used only after the object is created. The instance variable can be accessed by the object as well. Example: Account acct = new Account(100.0); Acct.deposit(200.0); Methods that don’t need access to instance variables are known as class methods (or static methods.) Example: SimpleIO.prompt, SimpleIO.readLine, Convert.toDouble, Integer.parseInt, Math.abs Math.max, Math.min, Math.pow, Math.round, Math.sqrt

3 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 3 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.

4 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 4 Class Methods Class methods have another important purpose: to specify where a program begins execution.  main is a class method, so every Java application has at least one class method. A class from which objects can be created is said to be instantiable. For example the Math class is not instantiable.

5 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 5 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.

6 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 6 7.2Writing Class Methods The declaration of a class method must contain the word static.

7 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 7 Access Modifiers for Class Methods Class methods that are intended for use by other classes should be declared public. Example: Math.round Class methods that are intended for use within a single class should be declared private. A modification of private method does not affect other classes.

8 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 8 7.3The 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;

9 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 9 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;

10 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 10 Example: A Dollar-Formatting Method Display amounts to dollars. cents. System.out.println won’t always provide the desired formatting: Example : 10.50  10.5 10000000.00  1.0E7. Also, amounts won’t be rounded to cents, so values such as 10.50001 may be printed.

11 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 11 Example: A Dollar-Formatting Method A class method that implements this strategy: private static String formatAsMoney(double amount) { //round the amount first 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; }

12 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 12 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.

13 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 13 Conditional Expressions expr1 ? expr2 : expr3 “if expr1 then expr2 else expr3.” The resulting expression is said to be a conditional expression. The conditional operator is a ternary operator, because it requires three operands. The conditional operator has lower precedence than all other operators except the assignment operators.

14 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 14 Conditional Expressions String result; if (cents <= 9) result = dollars + ".0" + cents; else result = dollars + "." + cents; return result; To: return (cents <= 9) ? (dollars + ".0" + cents) : (dollars + "." + cents); Or: return dollars + (cents <= 9 ? ".0" : ".") + cents;

15 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 15 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");

16 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 16 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

17 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 17 7.4Parameters How Arguments Are Passed. –by value : copies of arguments are passed by value. 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. –What happens when we change the value of a parameter?

18 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 18 How Arguments Are Passed Example 1: Assigning a new value to a parameter. private static void printStars(int numStars) { while (numStars-- > 0) System.out.print('*'); System.out.println(); } 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

19 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 19 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

20 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 20 How Arguments Are Passed When printStars was called, the value of n was copied into the numStars parameter: At the end of the method call, n is not changed.

21 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 21 How Arguments Are Passed Example 2: Modifying an object passed as an argument. private static void transferBalance( Account oldAccount, Account newAccount) { newAccount.deposit(oldAccount.getBalance()); oldAccount.close();}

22 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 22 How Arguments Are Passed An example in which transferBalance is called: Account acct1 = new Account(1000.00); Account acct2 = new Account(500.00); System.out.println(acct1.getBalance()” : “ + acct2.getBalance()); transferBalance(acct1, acct2); System.out.println(acct1.getBalance()” : “ + acct2.getBalance()); The output produced by these statements: 1000.00 : 500.00 0.00 : 1500.00

23 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 23 How Arguments Are Passed Account acct1 = new Account(1000.00); Account acct2 = new Account(500.00);

24 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 24 How Arguments Are Passed If we call: transferBalance(acct1, acct2);

25 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 25 How Arguments Are Passed As a result of calling transferBalance, the state of the acct1 and acct2 objects is changed:

26 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 26 Array Parameters Passing arrays to methods is much like passing objects. When an array is passed to a method, only a reference to the array is copied. As a result: 1.Passing an array to a method takes very little time. 2.A method can modify the elements of any array passed to it.

27 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 27 Array Parameters Example: private static void setElementsToZero(int[] a) { for (int i = 0; i < a.length; i++) a[i] = 0; } ======================================== int [] anArray = new int [10]; For (int i=0;i<anArray.length; i++) anArray[i]=i; System.out.println(anArray[3]); setElementsToZero(anArray); System.out.println(anArray[3]); The output produced by these statements: 3 0

28 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 28 Program Arguments program arguments (or command-line arguments) : any data supplied by the user on the command line How to use program arguments? After compiling, in command line: java MyProgram java MyProgram 100 200

29 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 29 Program Arguments How to write a program that accesses command- line arguments supplied by the user? In the main method : public static void main(String[] args) { … } In the example, java MyProgram 100 200 args[0] = “100”, args[1]=200.

30 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 30 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

31 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 31 Program Arguments The main method’s parameter doesn’t have to be named args ( “arguments”). You can change to any. The square brackets can go after args if desired: public static void main(String argv[]) { … } Typically, a program will use a loop to examine and process the command-line arguments.

32 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 32 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]); }

33 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 33 7.5Class Variables Class variables: Variables that belong to a class, but not to any particular instance of a class. Called static variables or static fields as well. Class variables are stored only once in the entire program.

34 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 34 Declaring Class Variables In declarations of class variables, static is inserted : 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.

35 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 35 Using Class Variables Outside of the class: Class-name.variable-name. Example: int accountsOpen = Account.numAccounts; Within the class, 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;

36 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 36 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.

37 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 37 Using Class Variables as Global Variables Only way to use global variables: a variable should be declared to be a public class variable. Avoid global variables, though. Global variables make programs harder to test and harder to modify. Can make many mistakes.

38 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 38 Class Variables in the System Class Example System.out.println The System class has three class variables: in, out, and err. Each variable represents a stream—a source of input or a destination for output. public static PrintStream out, err; Public static InputStream in; Accessed by System.in, System.out, and System.err.

39 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 39 The PrintStream Class PrintStream class provides the print and println methods. Example: 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.

40 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 40 Class Variables in the System Class System.in represents the standard input stream. By default, it is attached to the user’s keyboard. System.out represents the standard output stream. By default, it is displayed in the window System.err represents the standard error stream. By default, it is displayed in the same window as data written to System.out.

41 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 41 Redirecting the Standard Streams 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 Read from one file and write to another: java MyProgram myOutputFile If redirects, error messages written to System.out won’t appear on the screen. But, error messages written to System.err will still appear on the screen.

42 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 42 Using Class Variables as Constants Use final for a constant class variable. Example: public class Math { public static final double E = 2.7182818284590452354; public static final double PI = 3.14159265358979323846; … } E and PI are accessed by writing Math.E and Math.PI. Other examples of class variables used as constants: –Color.white, Color.black,... –Font.PLAIN, Font.BOLD, Font.ITALIC

43 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 43 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.

44 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 44 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.

45 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 45 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.

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

47 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 47 7.7Writing 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. – functions inside of a method. A helper method is to assist another method, not necessarily main. 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.

48 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 48 7.8Designing 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?

49 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 49 Designing Methods Consider.. –Cohesion: a method should perform a single, clearly defined task. –Stepwise refinement: dividing larger methods into smaller ones.  use helper methods. –Choosing method names wisely: easily understandable. –Parameters or class variables? –Return type


Download ppt "Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 7 Class."

Similar presentations


Ads by Google