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

时间:2014-12-03 00:02:18

标签: java arrays constructor

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

对于数组中的前三个位置,我想使用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");

2 个答案:

答案 0 :(得分:1)

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

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

使用这些字段和两个类包含的任何其他常用方法声明基类Person。然后,您将能够将数组声明为Person[][] Members;

public class Person {

  String firstName,lastName;
  int id;

  //constructors, getter and setter methods

}

然后Passenger和Pilot都可以像这样继承人:

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

    //constructors and methods that differentiate Pilots from Passengers.

}

答案 1 :(得分:0)

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