Late Binding / Virtual Method Invocation / Runtime Polymorphism / Dynamic Binding
In late binding we create the instance of the super class but call the constructor of the sub class, only to check if a upper class method is overridden in the in the sub class or not.
class A
{
int x = 10;
A()
{
System.out.println("Constructor in A");
}
void met1()
{
System.out.println("met1 in A");
}
void met2()
{
System.out.println("met2 in A");
}
}
class B extends A
{
int x = 20;
B()
{
System.out.println("Constructor in B");
}
void met1()
{
System.out.println("met1 in B");
}
void met3()
{
System.out.println("met3 in B");
}
}
class LateBinding
{
public static void main(String args[])
{
A m = new B();
System.out.println(m.x);
m.met1();
m.met2();
//m.met3();
}
}
OUTPUT : Compile Error – can not resolve symbol met3(). Comment it.
OUTPUT :
Constructor in A
Constructor in B
10
met1 in B
met2 in A
A m = new B(); is same as A m = new A();
B n = new B();
m = n;
Creating an object of class A and invoking the constructor of B which invokes constructor of A (super class).