Source of TestChildren.java


  1: import java.util.Scanner;

  3: /**
  4:  * A program to demonstrate inheritance using Parent and Child classes.
  5:  *
  6:  * @author Mark Young (A00000000)
  7:  */
  8: public class TestChildren {

 10:     public static void main(String[] args) {
 11:         Scanner kbd = new Scanner(System.in);

 13:         // Basic Parent (see slide 39)
 14:         Parent p = new Parent();
 15:         p.setValue("Frank");
 16:         System.out.println("Parent's value is: " + p.getValue());
 17:         kbd.nextLine();

 19:         // Basic Child (see slide 39)
 20:         Child1 c1 = new Child1();
 21:         c1.setValue("Fred");
 22:         c1.sayValue();
 23:         kbd.nextLine();

 25:         // Child with getValue that returns "Ba-ba"
 26:         Child2 c2 = new Child2();
 27:         c2.setValue("Fred");
 28:         c2.sayValue();
 29:         kbd.nextLine();

 31:         // Child with getValue that changes r to w
 32:         Child3 c3 = new Child3();
 33:         c3.setValue("Fred");
 34:         c3.sayValue();
 35:         kbd.nextLine();

 37:         // Inheritance and Polymorphism (see slide 45)
 38:         printValue("p", p);
 39:         printValue("c1", c1);
 40:         printValue("c2", c2);
 41:         printValue("c3", c3);
 42:         kbd.nextLine();

 44:         // And more (see slide 46)
 45:         // doThis(p);   // doesn't work -- expects Child1
 46:         doThis(c1);     // works -- c1 is a Child1
 47:         // doThis(c2);  // doesn't work -- expects Child1
 48:         // doThis(c3);  // doesn't work -- expects Child1
 49:         kbd.nextLine();
 50:     }

 52:     /**
 53:      * Print the "variable name" along with the value of that object.
 54:      * Say what type the object is.
 55:      *
 56:      * @param name the "variable name" -- as provided by the caller
 57:      * @param obj the object to call the getValue method on
 58:      */
 59:     public static void printValue(String name, Parent obj) {
 60:         System.out.println("The value of " + name + " is " + obj.getValue());
 61:         System.out.println("  (PS: " + name + " is a " 
 62:             + obj.getClass().getName() + ")");
 63:     }

 65:     /**
 66:      * Report that it's OK to call this method with this object as an argument
 67:      *
 68:      * @param obj the object that was passed to this method (duh!)
 69:      */
 70:     public static void doThis(Child1 obj) {
 71:         System.out.println("doThis works for a " + obj.getClass().getName());
 72:     }

 74: }