Source of TestChildren2.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 TestChildren2 {

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

 13:         // Parent with constructor
 14:         Parent2 p = new Parent2("Frank");
 15:         System.out.println("Parent's value is: " + p.getValue());
 16:         kbd.nextLine();

 18:         // Child with constructor
 19:         Child4 c4 = new Child4("Fred");
 20:         c4.sayValue();
 21:         kbd.nextLine();

 23:         // Child with extra field
 24:         Child5 c5 = new Child5("Harold", 21);
 25:         c5.sayValue();
 26:         kbd.nextLine();

 28:         // Inheritance and Polymorphism (see slide 45)
 29:         printValue("p", p);
 30:         printValue("c4", c4);
 31:         printValue("c5", c5);
 32:         kbd.nextLine();
 33:     }

 35:     /**
 36:      * Print the "variable name" along with the value of that object.
 37:      * Say what type the object is.
 38:      *
 39:      * @param name the "variable name" -- as provided by the caller
 40:      * @param obj the object to call the getValue method on
 41:      */
 42:     public static void printValue(String name, Parent2 obj) {
 43:         System.out.println("The value of " + name + " is " + obj.getValue());
 44:         System.out.println("  (PS: " + name + " is a " 
 45:             + obj.getClass().getName() + ")");
 46:     }

 48: }