Consider the following class definitions in a hypothetical Object Oriented language that supports inheritance and uses dynamic binding. The language should not be assumed to be either Java or C++, though the syntax is similar.
Class P {
Class Q subclass of P {
void f(int i) {
void f(int i) {
print(i);
print(2*i);
}
}
}
}
Now consider the following program fragment:
P x = new Q();
Q y = new Q();
P z = new Q();
x.f(1); ((P)y).f(1); z.f(1);
Here ((P)y) denotes a typecast of y to P. The output produced by executing the above program fragment will be
View worked solution
Answer: D
The language is specified to use dynamic binding (runtime polymorphism). Under dynamic binding, the method to be executed is determined at runtime based on the actual object type, not the declared reference type.
x.f(1);: The referencexis of typeP, but the actual object is of typeQ. Dynamic binding invokesQ's version off, printing .((P)y).f(1);: The referenceyis cast toP, but the underlying object remains of typeQ. Dynamic binding still resolves toQ's version off, printing .z.f(1);: The referencezis of typeP, but the actual object is of typeQ. This invokesQ's version off, printing .
Thus, the output produced is 2 2 2, which corresponds to Option D.
Free practice · Your answers on this page are not saved.
