Demonstrates the result of late binding. - Java Object Oriented Design

Java examples for Object Oriented Design:Inheritance

Description

Demonstrates the result of late binding.

Demo Code

class MyClass extends MyBase{
    public void print() {
        System.out.println("Inside MyClass.print()");
    }/*from w ww . ja  v  a2 s  .c  o m*/
}
 class MyBase {
    public void print() {
        System.out.println("Inside MyBase.print()");
    }
}

public class Main {
  public static void main(String[] args) {
    MyBase lbSuper = new MyBase();
    MyClass lbSub = new MyClass();

    // Will access MyBase.print() 
    lbSuper.print(); // #1 

    // Will access MyClass.print() 
    lbSub.print();   // #2 

    // Will access MyClass.print() 
    ((MyBase)lbSub).print(); // #3 

    // Assign the lbSub to lbSuper 
    lbSuper = lbSub; // Upcasting 

    // Will access MyClass.print() 
    lbSuper.print(); // #4 
  }
}

Result


Related Tutorials