Reputation: 5
I am trying to write a program that takes objects that are created in one class and place them in a constructor of another class. I do not understand the general concept of that. I am not looking for the answer to the code but I am looking for the general reasons why it works so that I can understand what to do.
Here is the code I am trying to take four instances of the object Ship and place them into Fleet. I don't need the specific answer just something so that I understand how to take objects created from one class into the constructor of another.
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
Upvotes: 0
Views: 3746
Reputation: 13334
If the purpose of Fleet
constructor to assign values to the four Ship
variables, you do it the same way as with any other constructor:
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
}
Upvotes: 0
Reputation: 165
So the way that another class "holds" objects of another class in Java is that it stores references to them. So when you create ship1, you allocate a spot in memory for ship1, and its instance variables. Then when you pass it as a parameter in Fleet, Fleet stores a reference essentially saying "ship1 is stored in this memory location", then when you use it from another method inside fleet, it manipulates ship1, by going to that memory location.
Upvotes: 0
Reputation: 31184
What you're missing is the actual invocation of the constructor. All you're really doing is defining parameters that can be passed into your constructor.
You actually pass the objects in like this.
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);
Upvotes: 1