Polymorphism

Nicholas Duchon: Mar 21, 2018.

Outline

  • ClassB extends ClassA


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

> Note that cc is declared of type ClassA, but is actually an object of type ClassB!
Thus, the runtime environment (JVM) determines the version of the method run to call by the starting in the class of the actual type of the object, not the declared type.

// 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


ND.