Bird
0
0

What will be the output of this code?

medium📝 Predict Output Q4 of 15
Java - Classes and Objects

What will be the output of this code?

class Engine {
  void start() { System.out.println("Engine started"); }
}
class Car {
  Engine engine = new Engine();
  void startCar() { engine.start(); }
}
public class Test {
  public static void main(String[] args) {
    Car car = new Car();
    car.startCar();
  }
}
AEngine started
BCar started
CNothing prints
DCompilation error
Step-by-Step Solution
Solution:
  1. Step 1: Trace method calls

    The main method creates a Car object, then calls startCar(), which calls engine.start().
  2. Step 2: Check output of engine.start()

    engine.start() prints "Engine started" to the console.
  3. Final Answer:

    Engine started -> Option A
  4. Quick Check:

    Method call chain output = "Engine started" [OK]
Quick Trick: Method calls inside objects print expected messages [OK]
Common Mistakes:
  • Expecting Car started instead of Engine started
  • Thinking no output prints
  • Assuming compilation error due to nested calls

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes