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 Class Methods.

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 Class Methods."— Presentation transcript:

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

3 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING 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(1000.00); 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();

4 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING 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.

5 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING 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.

6 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 6 Class Methods Class methods used in Chapter 2: Double.parseDouble Integer.parseInt Math.abs Math.max Math.min Math.pow Math.round Math.sqrt

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

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

9 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 9 Declaring Class Methods Example of a class method declaration:

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

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

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

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

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

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

16 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 16 CourseAverage2.java // Program name: CourseAverage2 // Author: K. N. King // Written: 1998-04-21 // Modified: 1999-04-18 // // 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 10% // Test 1 15% // Test 2 15% // Final exam 30% // // The course average is rounded to the nearest integer.

17 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 17 import java.util.Scanner; 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) { Scanner sc = new Scanner(System.in); // Print the introductory message System.out.println("Welcome to the CSc 2310 average " + "calculation program.\n");

18 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 18 // Prompt the user to enter program scores and compute // the average of the scores double programAverage = readProgramScores(sc) / 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(sc) / NUM_QUIZZES; // Leave a blank line System.out.println(); // Prompt the user to enter scores on the tests and final // exam double test1 = readDouble(sc,"Enter Test 1 score: "); double test2 = readDouble(sc,"Enter Test 2 score: "); double finalExam = readDouble(sc,"Enter Final Exam score: ");

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

20 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 20 /////////////////////////////////////////////////////////// // 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(Scanner sc) { double programTotal = 0.0; for (int i = 1; i <= NUM_PROGRAMS; i++) programTotal += readDouble(sc,"Enter Program " + i + " score: "); return programTotal; }

21 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 21 /////////////////////////////////////////////////////////// // 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(Scanner sc) { double quizTotal = 0.0; for (int i = 1; i <= NUM_QUIZZES; i++) quizTotal += readDouble(sc,"Enter Quiz " + i + " score: "); return quizTotal; }

22 Chapter 7: Class Variables and Methods Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 22 /////////////////////////////////////////////////////////// // 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(Scanner sc, String prompt) { System.out.print(prompt); String userInput = sc.nextLine(); return Double.parseDouble(userInput); }


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

Similar presentations


Ads by Google