Writing Constructors for Subclasses

AP Computer Science A· difficulty 3/5

public class Vehicle {
    private int wheels;
    public Vehicle(int w) { wheels = w; }
}
public class Car extends Vehicle {
    private String model;
    public Car(String m) {
        model = m;
    }
}

What happens when you try to compile Car?

  • A

    Warning but compiles

  • B

    Compiles successfully

  • C

    Compile error: no default constructor in Vehicle to call implicitly

    check_circle
  • D

    Runtime error when instantiated

Explanation

When a subclass constructor does not explicitly call super(...), Java inserts an implicit super() with no arguments. Since Vehicle has no zero-argument constructor, this fails to compile.

Want 10 more like this — adaptive to your weak spots?

Related questions