[英]Calling a Class in the constructor of another class in java
我正在尝试编写一个程序,该程序接受在一个类中创建的对象并将它们放在另一个类的构造函数中。 我不了解这个一般概念。 我不是在寻找代码的答案,而是在寻找它起作用的一般原因,以便我理解该怎么做。
这是我尝试获取对象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
您缺少的是构造函数的实际调用。 您真正要做的就是定义可以传递给构造函数的参数。
您实际上是这样传递对象的。
Ship ship1 = new Ship("sailboat", 5);
Ship ship2 = new Ship("sailboat", 5);
Ship ship3 = new Ship("sailboat", 5);
Ship ship4 = new Ship("sailboat", 5);
Ship ship5 = new Ship("sailboat", 5);
Fleet myFleet = new Fleet(ship1, ship2, ship3, ship4, ship5);
因此,另一个类在Java中“持有”另一个类的对象的方式是它存储对它们的引用。 因此,当您创建ship1时,您会在内存中为ship1及其实例变量分配一个位置。 然后,当您在Fleet中将其作为参数传递时,Fleet会存储一个引用,该引用本质上说“ ship1存储在此内存位置”,然后从Fleet内部的另一种方法使用它时,它将通过转到该内存位置来操纵ship1。
如果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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.