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