1 Playing with Puppers
Suppose we have the Dog and Corgi classes which are a defined below with a few
methods but no implementation shown. (modified from Spring ’16, MT1)
1 | 1 public class Dog { |
For the following main method, at each call to play or bark, tell us what happens at
runtime by selecting which method is run or if there is a compiler error or runtime
error.
1 | 1 public static void main(String[] args) { |
2 Cast the Line
Suppose Cat and Dog are two subclasses of the Animal class and the Tree class is
unrelated to the Animal hierarchy. All four classes have default constructors. For
each line below, determine whether it causes a compilation error, runtime error, or
runs successfully. Consider each line independently of all other lines. (extended
from Summer ’17, MT1)
1 | 1 public static void main(String[] args) { |
3 SLList Vista
(Slightly adapted from Summer 2017 MT1) Consider the SLList class, which represents
a singly-linked list. A heavily abridged version of this class appears below:
1 | 1 public class SLList { |
You think to yourself that the behavior of indexOf could be a bit confusing, so you
decide it should throw an error instead. In the space below, write a class called
SLListVista which has the same exact functionality of SLList, except SLListVista’s
indexOf method produces a NoSuchElementException in the case that x is not in
the list.
Since we have not covered exceptions yet, the following line of code can be used to
produce a NoSuchElementException:
1 | throw new NoSuchElementException(); |
4 Dynamic Method Selection
Modify the code below so that the max method of DMSList works properly. Assume
all numbers inserted into DMSList are positive. You may not change anything in
the given code. You may only fill in blanks. You may not need all blanks. (Spring
’17, MT1)
1 public class DMSList {
2 private IntNode sentinel;
3 public DMSList() {
4 sentinel = new IntNode(-1000, new LastIntNode());
5 }
6 public class IntNode {
7 public int item;
8 public IntNode next;
9 public IntNode(int i, IntNode h) {
10 item = i;
11 next = h;
12 }
13 public int max() {
14 return Math.max(item, next.max());
15 }
16 }
17 public class LastIntNode extends IntNode {
public LastIntNode() {
super(0, null);
}
@Overwrite
public int max() {
return 0;
}
26 }
27 public int max() {
28 return sentinel.next.max();
29 }
30 }