繁体   English   中英

如何在同一个2D数组中使用两个构造函数? Java的

[英]How to use two constructors in the same 2D array? Java

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

对于数组中的前三个地方,我想使用“飞行员”类,而对于其他地方,则要使用“旅客”类。

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的一个很好的例子。

如果飞行员和乘客都是相同基类的子类,则可以正常工作。 例如,两个类都可能包含相似的字段,例如name和id。

用这些字段和两个类都包含的任何其他公共方法声明基类Person。 然后,您将可以将该数组声明为Person[][] Members;

public class Person {

  String firstName,lastName;
  int id;

  //constructors, getter and setter methods

}

然后,乘客和飞行员都可以像这样从Person继承:

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

    //constructors and methods that differentiate Pilots from Passengers.

}

创建Object类的数组或为PilotsPassengers定义父类,然后创建您的超类的数组。 您将能够将任何子类对象添加到父类数组。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM