java - 使用 super() 时幕后发生了什么

标签 java oop inheritance subclass superclass

我很想知道当您使用 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/

相关文章:

java.nio.Buffer 未在运行时加载 clear() 方法

JAVA - 不允许按住跳跃按钮

java - java中随机唯一的字母数字字符串

javascript - 避免需要为 javascript 原型(prototype)函数声明 'var me = this'

.net - .Net 继承和成员可见性的奇怪问题

c# - 接口(interface)会在子类中自动实现吗?

scala - Spray-json序列化继承案例类

java - 当我开始运行我的项目 spring boot Process 时,退出代码为 1 且异常属性为 'proxyBeanMethods'

c# - 覆盖 C# 中固有属性的继承

php - 将文件包含在我的类(class)中的最佳方式是什么?我正在做的事情经常中断