Wednesday 27 February 2013

20. What will happen when you attempt to compile and run the following code?

20.  What will happen when you attempt to compile and run the following code?

Choices:
a. Derived.amethod()
-1
Derived.amethod()
b. Derived.amethod()
99
c.Derived.amethod()
99
d. Derived.amethod()
e.Compile time error

Answer:-
B is correct.
The reason is that this code creates an instance of the Derived class but assigns it to a reference of a the Base class.
In this situation a reference to any of the fields such as i will refer to the value in the Base class, but a call to a method will refer to the method in the class type rather than its reference handle.
But note that if the amethod() was not present in the base class then compilation error would be reported as at compile time, when compiler sees the statement like b.amethod(), it checks if the method is present in the base class or not.
Only at the run time it decides to call the method from the derived class.

No comments:

Post a Comment