/**
 * This class demonstrates using dynamic dispatch, slightly different from
 * the original version.
 * 
 * Made the Parent and Child classes static and private to this class so that  
 * the variations of the dynamic dispatch example can exist in the same 
 * (default) package.
 *
 * @author Sara Sprenkle
 *
 */
public class AnotherDynamicDispatchExample {  
    
    public static void main(String[] args) {
        Parent p = new Parent();
        Child c = new Child();
        Parent p2 = new Child();
        
        p.method1();
        System.out.println("");

        c.method1();
        System.out.println("");
        
        p.method2();
        System.out.println("");

        c.method2();
        System.out.println("");
        
        // Same behavior as calling method2 on the Child object variable
        // because the object referred to by p2 is a Child object.
        p2.method2();
        System.out.println("");
        
        // However, the following code would not compile because p2 is a 
        // Parent object variable, and the Parent class does not define
        // the childOnlyMethod:
        
        // p2.childOnlyMethod();
        
        // Demonstrates how you could call the childOnlyMethod:
        if( p2 instanceof Child ) { // We know that this is the case.
        	Child p2AsChild = (Child) p2;
        	p2AsChild.childOnlyMethod();
        }
    }
    
    static private class Parent {
 
		public Parent() {
		}
		
		public void method1() {
			System.out.println("Parent: method1");   
		}
		
		public void method2() {
			System.out.println("Parent: method2");
			method1(); 
		}
		
	}
	
	static private class Child extends Parent {
	 
		public Child() {
		}
		
		@Override
		public void method1() {
			System.out.println("Child: method1");   
		}
		
		/** 
		 * A brand new method!
		 */ 
		public void childOnlyMethod() {
			System.out.println("Child: child-only method");	
		}
		
	}
}



