Question 1-4

[10 pts] Suppose we have the following two class definitions.

class P {
  public int f(int x) {
    return x + 1;
  }
  public int g(int x) {
    return f(x + 2);
  }
}
class Q extends P {
  public int f(int x) {
    return x + 4;
  }
  public int h(int x) {
    return f(x + 8);
  }
}
And suppose we execute the following run method.
public static void run() {
  P a = new P();
  Q b = new Q();
  P c = b;
  IO.println(a.f(0) + " " + a.g(0));
  IO.println(b.f(0) + " " + b.g(0) + " " + b.h(0));
  IO.println(c.f(0) + " " + c.g(0));
}
What would the method print?

Solution

1 3
4 6 12
4 6

Back to Midterm 1