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());- A. 100
- B. 0
- C. Compilation error: setSpeed is protected and inaccessible
- 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
- What is printed? cpp class Stack { vector<int> data; public: void push(int x) { data.pushback(x); } int pop() { int top = data.back()…
- What is printed? java interface Repository<T> { void save(T item); T find(int id); } class UserRepository implements Repository<String> {…
- What is printed? cpp class Printable { public: virtual void print() const = 0; virtual ~Printable() = default; }; class Report : public…
- What is printed? java class Shape implements Comparable<Shape> { double area; Shape(double a) { area = a; } public int compareTo(Shape o)…
- What is printed? java class Base { public Object process() { return "base-result"; } } class Derived extends Base { @Override public…
- What is printed? cpp class Logger { public: static Logger& instance() { static Logger inst; return inst; } void log(const string& msg) {…