1
package vehicleapp;

public class Car extends Vehicle {
    int seatCap;

    public Car(String name, int modelNo, int seatCap) {
        this.seatCap = seatCap;
        super(name, modelNo);
    }
}

What's the problem in this code?

Cœur
  • 37,241
  • 25
  • 195
  • 267

5 Answers5

3

super(name, modelNo); must be the first statement in the constructor body (whenever you include it explicitly), since the super class constructor must be executed prior to the body of the sub-class constructor :

public Car(String name, int modelNo, int seatCap) {
    super(name, modelNo);
    this.seatCap = seatCap;
}
Eran
  • 387,369
  • 54
  • 702
  • 768
1

In any constructor call, super must be the first line if it is being used. docs.oracle.com/javase/tutorial/java/IandI/super.html

super(name, modelNo);
dildeepak
  • 1,349
  • 2
  • 16
  • 34
0

Use super() as the first line inside your constructor for the reason as shared in an SO-answer here - why-does-this-and-super-have-to-be-the-first-statement-in-a-constructor and you can change your existing code as -

public Car(String name, int modelNo, int seatCap) {
    super(name, modelNo);
    this.seatCap = seatCap;
}
Community
  • 1
  • 1
Naman
  • 27,789
  • 26
  • 218
  • 353
0

In your Vehicleapp package

Your vehicle class must be like this

public class Vehicle{
private String name,modelNo;
    Vehicle(String name ,String modelNo)
    {
          this.name=name;
          this.modelNo=modelNo;
    }
}
0

The Super(); keyword should be in the top as you are creating a constructor in the child class, the constructor first looks for the superClass constructor and till the Object SuperClass.

Hirearchy:

child Contrctor-> (looks for parent Constructor) ->ParentClass ->(If it is also inheriting for any superClass it should have superclass's superClass constructor i.e Super();) ->... ->Object SuperClass.

Usually we have the keyword super(); in all the user defined Constructor, but being obvious its not written.

Sumit Sagar
  • 342
  • 1
  • 6
  • 17