Originally posted by Abhishek Reddy Chepyala:
class A
{
protected void meth()
{
System.out.println("meth() of A called");
}
}
class B extends A
{
protected void meth()
{
System.out.println("meth() of B called");
}
}
class C extends B
{
public static void main(String args[])
{
C c=new C();
A a=(A)c;
a.meth();//------which method is invoked and why-
System.out.println("exited main");
}
}
In the above code i typecasted the "c" reference to A type. When i invoke the method meth() on "a" reference method meth() of class B is invoked rather than Class A method..why is that so..
Ok Let me explain,
Please correct me other ranchers If I am wrong,
Prior to explain this I would like to introduce one example
What do you think the output is?
Correct Output is:
in child Anyways now as you see in the your code that
C is direct subclass of Class B
So it will search the called method in it body itself but if it failed then it goes into the direct superclass that is
B There it found the method so it executes the method given in Class
B It is the exmple of run Time Binding.
Check this out
PolyMorphism-Run Time Binding