ProgrammingHardGATE CS · TCS NQT Prime · Product Company SDE
java class Base { int v = 1; } class Derived extends Base { int v = 2; } // main: Base b = new Derived(); System.out.print(b.v); What is printed?
class Base { int v = 1; }
class Derived extends Base { int v = 2; }
// main:
Base b = new Derived();
System.out.print(b.v);What is printed?- A. 2
- B. 1
- C. 0
- D. Compile error
Correct answer: B. 1
Fields are not polymorphic in Java either; b.v is resolved using b's declared type Base, so it reads Base's v, which is 1, even though the object is really a Derived.
More OOP with C++ and Java questions
- In C++, a base class constructor calls a function that is overridden in a derived class. Which version actually runs while the base…
- A PaymentMethod type requires every concrete implementation to provide charge() and refund(), but there is no shared implementation at all…
- Which kind of call in C++ is resolved using static (compile-time) binding rather than dynamic (run-time) binding?
- Which of these can a Java interface still NOT have, even in a modern version such as Java 17?
- A class overrides equals() but does not override hashCode(). What bug does this risk for instances used as keys in a HashMap or stored in…
- Which run-time mechanism lets a call through a base-class pointer invoke the correct derived-class override in C++?