ProgrammingHardWipro · Cognizant pattern

What is printed?

What is printed?
class Vehicle {
    private int speed;
    protected void setSpeed(int s) { speed = s; }
    int getSpeed() { return speed; }
}
class Car extends Vehicle {
    void accelerate() { setSpeed(100); }
}
// in main:
Car c = new Car();
c.accelerate();
System.out.println(c.getSpeed());
  1. A. 100
  2. B. 0
  3. C. Compilation error: setSpeed is protected and inaccessible
  4. D. Compilation error: speed is private and inaccessible to Car

Correct answer: A. 100

speed itself is private to Vehicle and never directly touched by Car, but setSpeed() is protected, which is accessible to subclasses (including across packages, via the subclass itself); Car's accelerate() legally calls the inherited setSpeed(100), setting the private field indirectly: getSpeed() then returns 100.

More OOP with C++ and Java questions

Exams that ask this topic