我正在尝试编写一个程序,该程序接受在一个类中创建的对象并将它们放在另一个类的构造函数中。我不了解这个一般概念。我不是在寻找代码的答案,而是在寻找它起作用的一般原因,这样我才能理解该怎么做。
这是我尝试获取对象Ship的四个实例并将其放入Fleet中的代码。我只需要一些特定答案,就可以理解如何将从一个类创建的对象带入另一个类的构造函数。
public class Ship {
// instance variables
private String shipType; // The type of ship that is deployed in a fleet.
private int fuelTankSize; // The fuel that each ship has at the start.
private double currentFuelLevel; // the change in fuel either consumed or added.
// constuctors
// takes in the shiptype and fuelunits to be set in the driver.
public Ship(String inShip, int inFuel) {
shipType = inShip;
fuelTankSize = inFuel;
currentFuelLevel = inFuel;
}
public class Fleet
{
// instance variables
// constructor
public Fleet(Ship ship1, Ship ship2, Ship ship3, Ship ship4){
}
//methods
最佳答案
如果Fleet
构造函数的目的是将值分配给四个Ship
变量,则可以使用与其他任何构造函数相同的方式进行操作:
public class Fleet
{
// instance variables
Ship ship1;
Ship ship2;
Ship ship3;
Ship ship4;
// constructor
public Fleet(Ship ship1, Ship ship2, Ship ship3, Ship ship4){
this.ship1 = ship1;
this.ship2 = ship2;
this.ship3 = ship3;
this.ship4 = ship4;
}
//methods
}