gpt4 book ai didi

java - 继承:是在父类(super class)内部复制内容吗?

转载 作者:行者123 更新时间:2023-11-30 06:05:53 25 4
gpt4 key购买 nike

以下代码来自 https://www.geeksforgeeks.org/inheritance-in-java/

//Java program to illustrate the 
// concept of inheritance

// base class
class Bicycle
{
// the Bicycle class has two fields
public int gear;
public int speed;

// the Bicycle class has one constructor
public Bicycle(int gear, int speed)
{
this.gear = gear;
this.speed = speed;
}

// the Bicycle class has three methods
public void applyBrake(int decrement)
{
speed -= decrement;
}

public void speedUp(int increment)
{
speed += increment;
}

// toString() method to print info of Bicycle
public String toString()
{
return("No of gears are "+gear +"\n" + "speed of bicycle is "+speed);
}
}

// derived class
class MountainBike extends Bicycle
{

// the MountainBike subclass adds one more field
public int seatHeight;

// the MountainBike subclass has one constructor
public MountainBike(int gear,int speed, int startHeight)
{
// invoking base-class(Bicycle) constructor
super(gear, speed);
seatHeight = startHeight;
}

// the MountainBike subclass adds one more method
public void setHeight(int newValue)
{
seatHeight = newValue;
}

// overriding toString() method
// of Bicycle to print more info
@Override
public String toString()
{
return (super.toString()+ "\nseat height is "+seatHeight);
}

}

// driver class
public class Test
{
public static void main(String args[])
{

MountainBike mb = new MountainBike(3, 100, 25);
System.out.println(mb.toString());

}
}

嘿伙计们,我想仔细检查一下下面的说法是否正确:

当创建 My_Calculation 类的对象时,会在其中创建父类(super class)内容的副本。

我的问题是:

当子类继承父类(super class)时,它实际上会复制其中的所有内容吗(这意味着父类(super class)和子类都有重复的字段,如 gearspeed ...等)

gearspeedsubclass只是对 superclass 的引用字段?

最佳答案

不,没有任何内容被“复制”到子类中。您的 MountainBike 是具有一组字段的单个对象。其中一些字段在 MountainBike 类中声明,另一些在其 Bicycle 父类(super class)中声明,但您的对象上仍然只有一组字段。

通过IDE中的调试器运行此代码,然后您可以查看对象的结构。

关于java - 继承:是在父类(super class)内部复制内容吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51354984/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com