我很想知道当您使用 super()
调用父类(super class)的构造函数时,幕后实际发生了什么。当一个对象从子类实例化时,子类是否继承父类(super class)对象?或者它是如何工作的?
这是我的引用代码:
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;
}
子类:
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;
}
最佳答案
没有超对象和子类对象。它只是一个对象,除了可能从父类继承的字段外,还具有在子类中声明的字段。
当 super
被调用时,JVM调用父类的构造函数来初始化从父类继承的字段。在幕后,构造函数转换为名为 <init>
的 JVM 指令。为字段赋值。
凭直觉你可以把它想象成这样:
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;
}
关于java - 使用 super() 时幕后发生了什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33843244/