I saw the code below online and the subclass constructor calls the superclass constructor before initialising its own variable (i.e. public int seatHeight
), after I change the order of initialisation, i.e. by putting seatHeight = startHeight;
before super(startCadence, startSpeed, startGear);
, my IDE displays error message. I was just wondering what is the reason behind calling superclass constructor before the subclass can initialise its own variable? And what are some of the rules governing superclass and subclass initialisation?
public class MountainBike extends Bicycle {
public int seatHeight;
public MountainBike(int startHeight, int startCadence,
int startSpeed, int startGear) {
super(startCadence, startSpeed, startGear);//when change order with seatHeight = startHeight, IDE display error
seatHeight = startHeight;
}
public void setHeight(int newValue) {
seatHeight = newValue;
}
}
A subclass is an extension of the superclass and can access any public/protected/package members and methods in the superclass.
The superclass cannot access members/methods of the subclass unless you cast this to the subclass. By straight OO, the superclass knows nothing about the subclass.
Since the subclass can access members/methods in the super class, the superclass must be initialized before the subclass so that any initial values, memory locations, whatever have valid beginning values.
BTW, this is true in all OO languages I've worked with, pretty sure this is a universal truth.