What happens behind the scenes when you use super ()

I am curious to know what really happens behind the scenes when you use super() to call the constructor of a superclass. When an object is created from a subclass, does the subclass in the object make a superclass? 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; } 
+7
java inheritance oop superclass subclass
source share
2 answers

There is no super object and subclass object. This is just one object with fields declared in a subclass, in addition to fields possibly inherited from the parent class.

When super is called, the JVM calls the constructor of the parent class to initialize the fields inherited from the parent class. Behind the scenes, the constructor is converted to a JVM instruction called <init> , which assigns values ​​to the fields.

So, intuitively, 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; } 
+5
source share

Thanks for answers! I just want to leave the resource I came across, and this explains it very well for those who are considering this issue.

We saw that the object belongs to the data type of the class from which it was created. For example, if we write

public MountainBike myBike = new MountainBike (); then myBike is of type MountainBike.

MountainBike comes from the bike and the facility. Therefore, MountainBike is a bicycle as well as an object, and it can be used wherever Bicycle or Object is located.

The converse is not necessarily true: the bike may be a MountainBike, but it is not necessary. Similarly, the object may be a bicycle or MountainBike, but this is not necessary.

0
source share

All Articles