📢 Too many exams? Don’t know which one suits you best? Book Your Free Expert 👉 call Now!

  • google app store apple app store
  • ✖

      Question

      The following Java code attempts to define an abstract

      class and use it. Identify the best way to correct the error to allow instantiation of a concrete class. abstract class Vehicle {     abstract void start();     void stop() {         System.out.println("Vehicle stopped.");     } } class Car extends Vehicle {     // Missing implementation } public class Main {     public static void main(String[] args) {         Car myCar = new Car();         myCar.start();     } }
      A Add `void start() { System.out.println("Car started."); }` to the `Car` class. Correct Answer Incorrect Answer
      B Remove the `abstract` keyword from the `start()` method in `Vehicle`. Correct Answer Incorrect Answer
      C Change `Vehicle` to an interface. Correct Answer Incorrect Answer
      D Make `Car` an abstract class as well. Correct Answer Incorrect Answer
      E Remove the `start()` method from `Vehicle`. Correct Answer Incorrect Answer

      Solution

      o In Java, if a class (like Vehicle) has an abstract method (start()), then that class itself must be declared abstract. o Any concrete class (a class that can be instantiated, like Car is intended to be) that extends an abstract class must provide an implementation for all inherited abstract methods. o Since Car does not implement start(), it is implicitly abstract and cannot be instantiated. To fix this, Car needs to provide a concrete implementation for the start() method.

      Practice Next
      ask-question