ch07
ch07
Why does the Coin class not depend on the CashRegister class?
Answer: None of the Coin operations require the CashRegister
class.
Continued
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Common Error: Trying to Modify Primitive Type Parameters
Continued
Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Common Error: Trying to Modify Primitive Type Parameters
• Example:
public class Financial
{
public static double percentOf(double p, double a)
{
return (p / 100) * a;
}
// More financial methods can be added here.
}
• Call with class name instead of object:
double tax = Financial.percentOf(taxRate, total);
Suppose Java had no static methods. How would you use the
Math.sqrt method for computing the square root of a
number x?
Answer:
Math m = new Math();
y = m.sqrt(x);
Harry tells you that he has found a great way to avoid those pesky
objects: Put all code into a single class and declare all methods
and variables static. Then main can call the other static
methods, and all of them can access the static variables. Will
Harry’s plan work? Is it a good idea?
Answer: Yes, it works. Static methods can access static
variables of the same class. But it is a terrible idea. As your
programming tasks get more complex, you will want to use
objects and classes to organize your programs.
• If all test cases pass, the JUnit tool shows a green bar: