Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's happening behind the scenes when you use super()

I'm curious to know what actually happens behind the scenes when you use super() to call a constructor of the super class. When an object is instantiated from the sub class, does the sub class inheret the super class object? or how does it work?

Here is my code for reference:

public class Bicycle {
//Declaring bicycles states
public int movSpeed = 0;
public int cadence = 0;
public int curGear = 0;

//Class constructor
public Bicycle(){
}

//Class constructor with params
public Bicycle(int movSpeed, int cadence, int curGear) {
    this.movSpeed = movSpeed;
    this.cadence = cadence;
    this.curGear = curGear;
}

Subclass:

public class mountainBike extends Bicycle {
//Declare mountainBikes states
public int frontTravel = 0;
public int rearTravel = 0;
public int gearMult = 0;

//Class constructor
public mountainBike(){
}

//Class constructor with params
public mountainBike(int movSpeed, int cadence, int curGear, int frontTravel, int rearTravel,int gearMult){
    super(movSpeed,cadence,curGear);
    this.frontTravel = frontTravel;
    this.rearTravel = rearTravel;
    this.gearMult = gearMult;
}
like image 955
user3307694 Avatar asked Nov 21 '15 12:11

user3307694


1 Answers

There is no super object and subclass object. It's just one object with fields declared in the subclass in addition to fields possibly inherited from the parent class.

When super is invoked, the JVM invokes the constructor of the parent class to initialize the fields inherited from the parent class. Behind the scenes the constructor translates to a JVM instruction called <init> that assigns values to the fields.

So intuitively you you can think of it as something like:

public mountainBike(int movSpeed, int cadence, int curGear, int frontTravel, int rearTravel,int gearMult) {
    // an object is created here
    // call the super constructor special method <init> 
    // which initializes  the inherited fields movSpeed, cadence, and curGear
    // initialize the below fields
    this.frontTravel = frontTravel;
    this.rearTravel = rearTravel;
    this.gearMult = gearMult;
}
like image 177
M A Avatar answered Oct 29 '22 18:10

M A