下面来自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类的对象时,将在其中创建超类内容的副本。
我的问题是:
当子类继承超类时,它实际上是否从其中复制所有内容(这意味着超类和子类都具有重复的字段,例如gear
,speed
...等)
或
gear
中的 speed
和subclass
只是对superclass
字段的引用?
答案 0 :(得分:1)
不,没有任何内容被“复制”到子类中。您的MountainBike
是具有一组字段的单个对象。其中的某些字段在MountainBike
类中声明,而某些字段在其Bicycle
超类中声明,但是对象上仍然只有一组字段。
通过IDE中的调试器运行此代码,然后您可以查看对象的结构。
答案 1 :(得分:0)
在创建派生类的对象时,该对象中包含基类的子对象。该子对象与您自己创建基类的对象相同。仅仅是从外部,基类的子对象被包装在派生类对象中。