Page 399 - Introduction to Programming with Java: A Problem Solving Approach
P. 399
§9.3 Class Methods
4. In Figure 9.2’s Mouse4 class, assume you have a method whose heading is public int getAge().
Suppose you want to call this method from another class. What’s wrong with the following statement?
int age = Mouse4.getAge();
5. Member access:
a) It is OK to use this in a class method. (T / F)
b) It is OK to use the class name as a prefix when calling a class method. (T / F)
c) Within a main method, it is OK to omit the class name prefix before the name of another class method
being called. (T / F)
6. It is legal to access a class member from an instance method and also from a constructor. (T / F)
7. It is legal to directly access an instance member from a class method. (T / F)
8. What are four common reasons for making a method a class method?
§9.4 Named Constants
9. What keyword converts a variable into a constant?
10. If you want a named constant used by instance methods to have the same value regardless of which object accesses it, the declaration should include the static modifier. (T / F)
11. A class constant should be initialized within a constructor. (T / F)
12. SupposeyouhaveagradingprogramthatinstantiatesmultipleexamobjectsfromanExamclass.Providea
declaration for a constant minimum passing score. Assume the minimum passing score for all exams is 59.5.
§9.5 Writing Your Own Utility Class
13. A utility class’s members should normally use the private and static modifiers. (T / F)
Exercises
Apago PDF Enhancer
Exercises 365
1. [after §9.2] Given a class with a class variable. All of the class’s objects get a separate copy of the class variable. (T / F)
2. [after §9.2] In general, why should you prefer local variables over instance variables and instance variables over class variables?
3. [after §9.2] Given a program that keeps track of book details with the help of a Book class, for each of the following program variables, specify whether it should be a local variable, an instance variable, or a class variable.
bookTitle (the title of a particular book) averagePrice (the average price of all of the books) price (the price of a particular book)
i (an index variable used to loop through all of the books)
4. [after §9.3] If a method accesses a class variable and also an instance variable, the method: a) must be a local method
b) must be an instance method
c) must be a class method
d) can be either a class method or an instance method—it depends on other factors
5. [after §9.3] If you attempt to directly access an instance method from within a class method, you’ll see an
error message like this:
Non-static <method-name> cannot be referenced from a static context
Normally, how should you fix the bug?