Actually What happen every time when you write such a code e.g.
It will search automatically in Base Class first and if there present then execute that method otherwise it checks the method declaration in Derived Class. This is the way of Execution. So this is a known behaviour of JAVA. SO don't be surpriced too much. .
Originally posted by Ajay A Patil: You can do it as follows:
This will not produce the results requested. Both examples will still call B's doit() method. In fact, I do not think there is any way to call A's doit() method from main unless you have an instance of A. An instance of B will always invoke B's doit() method, even if you have a reference to an A pointing to it.