Chapter 7: Inheritance – Method Behavior

Inheritance
Method behavior

Base and Derived classes are simple classes with one constructor and two methods

Parent class

public class Base
{
    public Base()
    {
        System.out.println("Constructor from Base class ");
    }
    public void methodOne()
    {
        System.out.println("methodOne from Base class");
    }
    public void methodTwo()
    {
        System.out.println("methodTwo from Base class");
    }
    
} 

Child class

public class Derived extends Base
{
    public Derived()
    {
        System.out.println("Constructor from Derived class " );
    }
    public void methodOne()
    {
        System.out.println("methodOne from Derived class");      
    }
    public void methodThree()
    {
        System.out.println("methodThree from Derived class");
    }    
}

    

Driver/Test class

public class BaseDerivedTest
{
    public static void main(String [] args)
    {
        Base b = new Derived();
        b.methodOne();
        b.methodTwo();
        //b.methodThree(); ERROR
        System.out.println("*** Derived ****");
        Derived c = (Derived)b;
        c.methodThree();
        Derived d = new Derived();
        d.methodOne(); 
        d.methodTwo();
        d.methodThree();
    }
}

Include these three classes in your project. Run the driver.

Study the code and the output from the driver class. Use the output to make conclusions based on the following:
1. Do you see a pattern in the order in which the constructor and methods are called? Clearly explain
2. What criteria does the order depend on?
3. Explain how late binding, Polymorphism has a role in the behavior.
Note: Include the output in your submission.

In preparation for the test on Monday work on these assignments:
Self-Review 7.1 through 7.8