当你使用super()时,背后发生了什么?

7

我很想知道在使用super()调用父类构造函数时,背后实际发生了什么。当从子类实例化一个对象时,子类是否继承了父类对象?或者它是如何工作的?

以下是我的参考代码:

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;
}

从技术上讲,你的 mountainBike(请使用UpperCamelCase来表示类)是一个 Bicycle,调用 super(args...) 告诉你正在调用特定的构造函数。如果你不带参数或者不调用 super(),则会调用默认构造函数。 - Emz
1
我猜你对Java还比较新,所以我也想指出原始默认值,没有必要将frontTravelrearTravel等的值设置为0,因为这是自动完成的。 - Emz
请查看《Head First Java》参考资料(第9章,“超类构造函数在对象生命周期中的作用”)。 - Yevgen
2个回答

5
没有超级对象和子类对象,只有一个对象,其中包含子类中声明的字段以及可能从父类继承的字段。当调用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;
}

0

感谢答案!我想分享一个资源,它很好地解释了这个问题。

我们已经看到,对象的数据类型是从实例化它的类来的。例如,如果我们写

public MountainBike myBike = new MountainBike(); 那么myBike就是MountainBike类型。

MountainBike是由Bicycle和Object派生而来的。因此,MountainBike是Bicycle,也是Object,并且可以在需要Bicycle或Object对象的任何地方使用。

反之不一定成立:自行车可能是山地自行车,但不一定是。同样,对象可能是自行车或山地自行车,但不一定是。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接