Implement the following class hierarchy on paper. You do not need to
fill in the method bodies for the toss
or bounce
methods.
Solutions:
public interface Tossable { void toss(); }
public abstract class Ball implements Tossable { private String brandName; public Ball(String brandName) { this.brandName = brandName; } public String getBrandName() { return brandName; } public abstract void bounce(); }
public class Baseball extends Ball { public Baseball(String brandName) { super(brandName); } public void toss() { } public void bounce() { } }
public class Football extends Ball { public Football(String brandName) { super(brandName); } public void toss() { } public void bounce() { } }
public class Rock implements Tossable { public void toss() { } }
Answer the following questions:
equals
method than to overload it?
If equals is overridden, then you end up with two equals methods for the same class. Which one gets called will depend on the argument type. This usually isn't the intended behavior. There should only be one notion of equality per class.
Variable Type | ||||||
Tossable | Ball | Rock | Baseball | Football | ||
Object Type | Tossable | — | — | — | — | — |
Ball | — | — | — | — | — | |
Rock | ✓ | X | ✓ | X | X | |
Baseball | ✓ | ✓ | X | ✓ | X | |
Football | ✓ | ✓ | X | X | ✓ |
1. Ball ball = new Football("spalding"); // CE 2. Ball ball = new Football("Spalding"); Baseball baseball = (Baseball)ball; // C // This will compile, but an exception will be thrown at run-time. // A variable of type Baseball can never contain an object of type // Football. 3. Object obj = new Baseball("spalding"); // CE 4. Object obj = new Baseball("spalding"); Tossable tossable = obj; // Neither // Tossable is less general than Object. The second assignment would // require a cast. 5. Tossable tossable = new Baseball("spalding"); Object obj = tossable; // CE