将一个子类对象添加到由超类数组制成的数组中,实现Java中的继承。

huangapple 未分类评论62阅读模式
英文:

Adding An Subclass Object To An Made of Superclass Array With Inheritance In Java

问题

所以我有两个类,分别是Flight和NonTransferFlight,Flight是NonTransferFlight的超类。我有一个名为FlightArray的数组,我创建它如下:

Flight flightArray[] = new Flight[10];

问题是,当我想将NonTransferFlight对象添加到这个数组时,它不允许我这样做。我该如何解决这个问题?

英文:

So I have two classes which are Flight and NonTransferFlight, and Flight is superclass of the NonTransferFlight. I have an array FlightArray which I created as:

Flight flightArray[] = new Flight[10];

Problem is, when I want to add an NonTransferFlight object to this array, it doesn't allow me to do that. how can I do that?

答案1

得分: 0

> 问题是,当我想向这个数组中添加一个 NonTransferFlight 对象时,它不允许我这样做。

我不太确定你为什么这样说,因为理论上你是可以这样做的。

如果你有如下的类结构(就像你描述的那样):

class NonTransferFlight extends Flight { }

class Flight { }

你可以很容易地将 NonTransferFlight 对象添加到你的数组中,如下所示:

Flight[] flightArray = new Flight[10];

flightArray[0] = new NonTransferFlight();
flightArray[1] = new Flight();
// ...

不相关,但是 作为一般规则,请使用 Java 风格的数组声明:Flight[] flightArray,而不是你在代码中的 C 风格数组声明:Flight flightArray[]

英文:

> Problem is, when I want to add an NonTransferFlight object to this array, it doesn't allow me to do that.

I'm not very sure why you say that, because, in theory, you can do that.

If you have the following class structure (as you described):

class NonTransferFlight extends Flight { }

class Flight { }

You can easily add NonTransferFlight objects to your array, as following:

Flight[] flightArray = new Flight[10];

flightArray[0] = new NonTransferFlight();
flightArray[1] = new Flight();
// ...

Not related, but as a general rule, please use Java-style array declaration: Flight[] flightArray, as opposed to what you have in the code, C-style array declaration: Flight flightArray[].

答案2

得分: 0

你可以像这样添加:

Flight flightArray[] = new Flight[10];
flightArray[0] = new NonTransferFlight();

或者

Flight flightArray[] = new Flight[10];
NonTransferFlight ntf = new NonTransferFlight();
// 可以为ntf实例设置一些属性,然后,
flightArray[0] = ntf;
英文:

You can add it like this:

Flight flightArray[] = new Flight[10];
flightArray[0] = new NonTransferFlight();

or

Flight flightArray[] = new Flight[10];
NonTransferFlight ntf = new NonTransferFlight();
// Can set some props for ntf instance and then,
flightArray[0] = ntf;

huangapple
  • 本文由 发表于 2020年4月9日 19:20:05
  • 转载请务必保留本文链接:https://java.coder-hub.com/61119976.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定