We can solve this problem using a question.
Q. When base class calls a method, how could the run time knows to called the overridden method in the derived class? The object is not even constructed yet.
A:
Why? From the language theory, it is called deferred binding or dynamic binding or binding at run time. Compiler leaves the decision to run time. To make the decision at run time, you don't need the object built first. The only thing you need to know is the type of the actual object.
In
Java, the Class (not class) object is load to the memory when it is first used. The run time knows it before any instance is constructed.
Look in your example:
Answer definitely should be 2) not 3) i.e b not c. Because if we think about run time binding and compile time binding then it should be clear. In your example very very important is that look the comments // in answer:
2)
RType.amethod // Before making any object.
99 // After making object.
RType.amethod // After making object.
So when you leave this decision at run time, it first find what type of object it is before making any instance of object. In your example,
Base b=new RType();
your Type is Base and your Base class has a Constructor and that constructor calls amethod(), which is overridden and after that
instance of object works.
Could i make you understand,
- Golam Newaz
------------------