Prashnikaप्रश्निका
Code
About
‹ Back to the paper

Question 26

1 mark

Computer ScienceISC Computer Science - Competency Focused Practice Questions (CISCE, August 2024)Short answerInheritance, Interfaces and Polymorphism

Answer the following question.

Study the given two classes below and identify the error if any, in the given code. class Vehicle {…

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);
    }
}

Answer

Answer

The error is in the Car constructor: the call super(colour, registration) is not the first statement of the constructor. In Java, a call to super() must always be the first statement in a constructor, so this gives a compile time error ("call to super must be first statement in constructor").