ProgrammingVery hardProduct company OA
What is printed?
What is printed?
class Base {
protected int code = 1;
}
class Derived extends Base {
int code = 2;
}
// in main:
Base b = new Derived();
System.out.println(b.code);- A. 2
- B. 1
- C. Compilation error: duplicate field code
- D. Runtime error
Correct answer: B. 1
Since fields are not polymorphic, accessing b.code uses the STATIC type of the reference (Base) to decide which field is accessed, regardless of the actual object's runtime type. It prints Base's own code, 1, not Derived's shadowing field 2.
More OOP with C++ and Java questions
- What is printed? java class Vehicle { void start() { System.out.print("Vehicle starts "); } } interface Electric { default void start() {…
- What is printed? java interface Counter { int next(); private int helper() { return 100; } default int nextPlusHelper() { return next() +…
- What is printed? cpp class Account { double balance = 0; friend void deposit(Account& a, double amt); public: double getBalance() const {…
- What is printed? java abstract class Shape { abstract double area(); } interface Colorable { String color(); } class Circle extends Shape…
- What is printed? java class Base implements Cloneable { int x = 5; @Override public Base clone() throws CloneNotSupportedException {…
- What is printed? java class Node<T extends Comparable<T>> { T value; Node(T v) { value = v; } boolean isGreaterThan(Node<T> other) {…