Inheritance Practice


Here's another copy of the practice problems I mailed out over Fall Break.  The initial setup:

class P {
   public void f1() {
      System.out.println("Pf1");
   }
   public void f2() {
      f1();
   }
   public char x = 'P';
}
class C extends P {
   public void f1() {
      System.out.println("Cf1");
   }
   public void f3() {
      System.out.println("Cf3");
   }
   public char x = 'C';
}

P p1 = new P();
P p2 = new C();
C c1 = new C();



Now, find the output (and why) for each of these lines.  Note that two of them won't compile at all.

p1.f1();
p2.f1();
c1.f1();

p2.f3();
c1.f3();
((P)c1).f1();
((P)c1).f3();

p1.f2();
p2.f2();
c1.f2();

System.out.println( p1.x );
System.out.println( p2.x );
System.out.println( c1.x );
System.out.println( ((C)p2).x );
System.out.println( ((P)c1).x );



Answers
Basic method calls
p1.f1(); -- Pf1
p2.f1(); -- Cf1
c1.f1(); -- Cf1

Compile-time static binding
p2.f3(); -- compile-time error
c1.f3(); -- Cf3
((P)c1).f1(); -- Cf1
((P)c1).f3(); -- compile-time error
Dynamic binding on this
p1.f2(); -- Pf1
p2.f2(); -- Cf1
c1.f2(); -- Cf1

Static binding of variables
System.out.println( p1.x ); -- P
System.out.println( p2.x ); -- P
System.out.println( c1.x ); -- C
System.out.println( ((C)p2).x ); -- C
System.out.println( ((P)c1).x ); -- P

Peter Flynn