簡體   English   中英

在Java中另一個類的構造函數中調用類

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM