Java examples for Object Oriented Design:Inheritance
Demonstrates the result of the early binding.
class MyBase {//from ww w . j a v a 2 s .c o m // An instance variable public String str = "EarlyBindingSuper"; // A static variable public static int count = 100; public static void print() { System.out.println("Inside EarlyBindingSuper.print()"); } } class MyClass extends MyBase{ // An instance variable public String str = "EarlyBindingSub"; // A static variable public static int count = 200; public static void print() { System.out.println("Inside EarlyBindingSub.print()"); } } public class Main { public static void main(String[] args) { MyBase ebSuper = new MyBase(); MyClass ebSub = new MyClass(); // Will access EarlyBindingSuper.str System.out.println(ebSuper.str); // Will access EarlyBindingSuper.count System.out.println(ebSuper.count); // Will access EarlyBindingSuper.print() ebSuper.print(); // Will access EarlyBindingSub.str System.out.println(ebSub.str); // Will access EarlyBindingSub.count System.out.println(ebSub.count); // Will access EarlyBindingSub.print() ebSub.print(); // Will access EarlyBindingSuper.str System.out.println(((MyBase)ebSub).str); // Will access EarlyBindingSuper.count System.out.println(((MyBase)ebSub).count); // Will access EarlyBindingSuper.print() ((MyBase)ebSub).print(); // Assign the ebSub to ebSuper ebSuper = ebSub; // Upcasting /* Now access methods and fields using ebSuper variable, which is referring to a EarlyBindingSub object */ // Will access EarlyBindingSuper.str System.out.println(ebSuper.str); // Will access EarlyBindingSuper.count System.out.println(ebSuper.count); // Will access EarlyBindingSuper.print() ebSuper.print(); } }