✏️ Explanatory Question

[Inheritance]

Study the given two classes below and identify the error, if any, in the given code.

class Vehicle
{
    protected String colour;
    protected String registration;

    public Vehicle(String c, String r)
    {
        colour = c;
        registration = r;
    }

    public void show()
    {
        System.out.println("Colour: " + colour);
        System.out.println("Registration number: " + registration);
    }
}

class Car extends Vehicle
{
    private double weight;
    private String model;

    public Car(String model, double weight,
               String colour, String registration)
    {
        this.model = model;
        this.weight = weight;

        super(colour, registration);
    }

    public void show()
    {
        super.show();

        System.out.println("Car Model name = " + model);
        System.out.println("Car body weight = " + weight);
    }
}

  

👁 0 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

Error: The statement super(colour, registration); must be the FIRST statement inside the constructor.

Understanding the Problem:

The class Car inherits the class Vehicle.

Therefore, the constructor of the parent class (Vehicle) is called using:

super(colour, registration);

Important Rule in Java:

The call to super() must always be the FIRST statement inside a constructor.

What is Wrong Here?

In the given constructor:

public Car(String model, double weight, String colour, String registration) { this.model = model; this.weight = weight; super(colour, registration); }

The statements:

this.model = model; this.weight = weight;

appear BEFORE the call to super().

This causes a:

Compile Time Error

Why Does Java Enforce This Rule?

Java first initializes the parent class before initializing the child class.

Therefore:

  • Parent constructor must execute first
  • Then child class constructor executes

Correct Constructor:

public Car(String model, double weight, String colour, String registration) { super(colour, registration); this.model = model; this.weight = weight; }

Step-by-Step Execution:

Step Action
1 Call parent constructor using super()
2 Initialize child class variables
3 Execute remaining constructor code

Important Concept:

super() → Calls Parent Class Constructor this() → Calls Current Class Constructor

Both super() and this() must always be the first statement inside a constructor.

Final Conclusion:

  • The code contains a compile-time error.
  • The statement: super(colour, registration); is placed incorrectly.
  • It must be written as the FIRST statement in the constructor.