15-100 Exam 2 (Wednesday, October 19, 2005)

Exam 2 Solutions

```//Question 1
class PiggyBank implements Comparable {
private int numberOfCoins;
private double balance;

//constructor
public PiggyBank() {
numberOfCoins = 0;
balance = 0.0;
}

public double getBalance() {
return balance;
}

public int getNumberOfCoins() {
return numberOfCoins;
}

public void addCoins(int pennies, int nickles, int dimes, int quaters) {
numberOfCoins += pennies + nickles + dimes + quaters;
balance += pennies*.01 + nickles *.05 + dimes*.10 + quaters*.25;
}

public String toString() {
return "Total balance: " + balance + ", total number of coins: " +
numberOfCoins;
}

public boolean equals(Object o) {
PiggyBank pb = (PiggyBank) o;
if (pb.numberOfCoins == this.numberOf coins && pb.balance == this.balance) {
return true;
}
return false;
}

//to make comparable (needs to implement Comparable and have this)
public int compareTo(Object o) {
PiggyBank pb = (PiggyBank) o;

//assuming balance is most important and numberOfCoins secondary
if (pb.balance != this.balance) {
return (int)((this.balance-pb.balance)*100);
}
if (pd.numberOfCoins != this.numberOfCoins) {
return this.numberOfCoins - pb.numberOfCoins;
}

//get down to here, know they are equal...
return 0;
}
}

//question 3 interface:
interface Movable {
public boolean isLiftable();
}
class Bicycle implements Movable {
public boolean isLiftable() {
if ((length*40) > 70) {
return false;
}
if (length > 4) {
return false;
}
return true;
}
}

class Box implements Movable {
public boolean isLiftable() {
if (weight > 70) {
return false;
}
if (lengthFt > 4 || widthFt > 4 || heightFt > 4) {
return false;
}
}
}

//question 4
A local variable is declared with in a method and it's scope is that method (a local
variable can also have a scope smaller than the method if it is declared inside of a
loop or other body inside the method.

//question 5
An instance variable is a variable that is declared inside of the class and outside
of any methods.  It is not static.  It's scope is the class and any method can use it.
It is called and instance variable because each instance of an the object that is
made has it's own instance (copy) of the variable.

//question 6
When the argument and instance variable have the same name there is a name-space
conflict.  This is resolved by java using the name to refer to the argument variable
and to refer to the instance variable you need to use this.nameOfVariable.

//question 7
The scope of the argument is more like the scope of a local variable because the
argument's scope is the whole method (just like a local variable's).
```