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

标签 java object inheritance memory

以下代码来自 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/

相关文章:

基于多个条件的javascript对象过滤器

javascript - 在 JavaScript 中,Object Literal Notation 不就是字典的别称吗?

python - 重复代码与多重继承

c++ - 如何验证我是在使用 C++ 中的基础对象还是派生对象?

java - 在 Java Swing 中显示运动图像

java - 当类实现接口(interface)时,该类是否继承接口(interface)中声明的抽象内部类?

java - scala 2.8 隐式 java 集合转换

java - (作业)Java错误: Incompatible Types

c++ - 使用统一初始化初始化对象和指针对象不起作用

c++ - 所有继承同一类的不同对象的单个容器