gpt4 book ai didi

java - 如何在同一个二维数组中使用两个构造函数? java

转载 作者:行者123 更新时间:2023-12-01 12:11:20 25 4
gpt4 key购买 nike

我想使用两个构造函数来区分同一数组中的两种类型的对象,尽管“类型不匹配”。所以我知道我必须以不同的方式声明数组,我只是不知道该怎么做。

对于数组中的前三个位置,我想使用 Pilots 类,对于其他位置,我想使用 Passenger 类。

public class Project_Space
{
public static void main(String[] args)
{
// 2D Array of Passengers objects- the Passengers class is in the Passengers.java file
//Pilot objects are constructed from Pilots.java file

Passengers[][] Members ;

int num_flights= 6; //create the "x" bound/size of the array

int num_passengers= 9; //create the "y" bound/size of the array

Members = new Passengers[num_flights][num_passengers]; //define the size of the array 6flights/9Passengers

//The Members array at index 0 is the first flight

//Members[0][0] = new Pilots(1,-1,"","","",0); //This spot in the array is for the Flight number in the first spot. Everything else are place holders for data that doesn't pertain to the company

Members[0][1] = new Pilots(1,"1877963200","Amadeus","Durrutti","Buckminster Cornwallis","1288211435", 11); //This spot in the array is for the first passenger of flight #1

Members[0][2] = new Pilots(2,"6054350085","Sirius","Sassafrass","Ali Bababa","1776812631", 9);

Members[0][3] = new Passengers(1,"7065253333","Amy","Hartman","Betty Sue","7708889999", 3, 50000,"0554055405540554");

Members[0][4] = new Passengers(2,"7545251337","Amanda","Zion","Beatrice Twix","7448656577", 4, 2000,"0554055405541111");

Members[0][5] = new Passengers(3,"8904448899","Janet","Graves","Neal Wade","4445556666", 5, 3000, "9031029266161432");

Members[0][6] = new Passengers(4,"8902234567","Kristen","Pickering","Christopher Soto","5685461208", 6, 51500, "0985028135114275");

Members[0][7] = new Passengers(5,"5000893778","Julianna","Estrada","Jill Hansen","2770779833", 7, 0, "0213595590286251");

Members[0][8] = new Passengers(6,"2080670437","Regena","Mckenzie","Vicki Cook","6224215759", 8, 250, "8204699533830238");

最佳答案

这是 OOP 的一个很好的例子。

如果飞行员和乘客都是同一基类的子类,则这将工作正常。例如,两个类可能包含相似的字段,例如名称和 ID。

使用这些字段以及这两个类包含的任何其他通用方法来声明基类 Person。然后您就可以将数组声明为 Person[][] Members;

public class Person {

String firstName,lastName;
int id;

//constructors, getter and setter methods

}

然后 Passenger 和 Pilot 都可以从 Person 继承,如下所示:

public class Pilot extends Person {
int totalHoursLogged;
String airline;
int salary;

//constructors and methods that differentiate Pilots from Passengers.

}

关于java - 如何在同一个二维数组中使用两个构造函数? java ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27261315/

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