Java - Inheritance and Late Binding

What is late binding?

Binding for non-static, non-final methods happens in late binding.

Demo

class MySuper {
  public void print() {
    System.out.println("Inside MySuper.print()");
  }/* w  w w.j  a va  2s  .c  o  m*/
}

class MySub extends MySuper {
  public void print() {
    System.out.println("Inside MySub.print()");
  }
}

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

    // Will access MySuper.print()
    lbSuper.print();

    // Will access MySub.print()
    lbSub.print();

    // Will access MySub.print()
    ((MySuper) lbSub).print();

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

    // Will access MySub.print() because lbSuper
    // is referring to a MySub object
    lbSuper.print();
  }
}

Result