Polymorphism - Musings

By: :Nicholas Duchon

An example examining how the Java system determines which method to call when confronted with polymorphic code.

// File: ClassA.java
// Date: Feb 15, 2013
// Author: Nicholas Duchon
// Purpose: check way polymorphism is resolved in Java
// Output:
//       1. aa.fun (aa): fun in ClassA
//       2. aa.fun (cc): fun in ClassA
//       3. bb.fun (bb): + fun (ClassB) in ClassB
//       4. bb.fun (cc): X fun (ClassA) in ClassB
//       5. cc.fun (bb): X fun (ClassA) in ClassB
//       6. cc.fun (cc): X fun (ClassA) in ClassB
// Conclusion:
//   > which class gets called is determined by the actual object at run time
//   > which method in that class is determined by the declared type at compile time

public class ClassA {
  public static void main (String args []) {
    ClassA aa = new ClassA ();
    ClassB bb = new ClassB ();
    ClassA cc = new ClassB ();
    System.out.printf ("1. aa.fun (aa): %s\n", aa.fun (aa));
    System.out.printf ("2. aa.fun (cc): %s\n", aa.fun (cc));
    System.out.printf ("3. bb.fun (bb): %s\n", bb.fun (bb));
    System.out.printf ("4. bb.fun (cc): %s\n", bb.fun (cc));
    System.out.printf ("5. cc.fun (bb): %s\n", cc.fun (bb));
    System.out.printf ("6. cc.fun (cc): %s\n", cc.fun (cc));
  } // end main
  public String fun (ClassA x) {return "fun in ClassA";}
} // end class ClassA

class ClassB extends ClassA {
  public String fun (ClassB y) {return "+ fun (ClassB) in ClassB";}
  public String fun (ClassA z) {return "X fun (ClassA) in ClassB";}
} // end