Monday, October 26, 2009

Pg. 367 Exercise 10

In the PennyJar.java program it is legal to remove the PennyJar. from the "PennyJar.allPennies++;" and "if(PennyJar.allPennies >= PennyJar.GOAL)" because the allPennies variable is class variable, and the GOAL variable is a constant variable.

However, in the PennyJarDriver.java program it is illegal to remove the PennyJar. from the "System.out.println(PennyJar.getAllPennies());" because getAllPennies() is a method declared in the PennyJar class. Without the PennyJar. in the statement the compiler cannot find the method.

If PennyJar. is omitted from the PennyJar.java program, but not from the PennyJarDriver.java, then the program executes normally.

Pg. 366 Exercise 6

public class Test{
private int x;
private static int y;
public void doIt(){
x = 1;
y = 2;
}
public static void tryIt(){
x = 3;
y = 4;
}
public static void main(String[] args){
doIt();
tryIt();
Test t = new Test();
t.doIt();
Test.doIt();
Test.tryIt();
}
}//end of Test class

1. "x" is not declared as a class variable; therefore, it cannot be referenced in a static method.
2. "doIt()" is not declared as a static method; therefore, it cannot be referenced in a static method. A constructor should be added.
3. For the same reason that error 2 occurred, "doIt()" cannot be called in a static method.