-2

i have a class constructor

public Knapsack(Item[] items){
       // to do
      }

Then I have and Item class that takes two arguments string and int. so for example

Knapsack k = new Item("Pen", 15);

when this object is passed into my constructor in other class how do I can use only single arguments such as "PEN" and int 15

marcellio
  • 32
  • 9
  • 1
    You can create multiple constructors for the same class and initialise the different behaviour in each constructor. This is generally called [overloading](https://stackoverflow.com/q/1182153/10400050) – Johan Oct 20 '18 at 19:20
  • 1
    That object can't be passed. It needs to be in an array – OneCricketeer Oct 20 '18 at 19:21

2 Answers2

1

You should pass an array to constructor like this:

Knapsack k = new Knapsack(new Item[]{new Item("Pen", 15)});

Also, if you want to pass literal values to Knapsack class and not the Item's array, then you can apply the Builder pattern here.

slesh
  • 1,902
  • 1
  • 18
  • 29
0

You need an array of items, as the constructor says. A Knapsack cannot be assigned to an Item

For example

Item[] items = new Item[1];
items[0] = new Item("Pen", 15);

Knapsack k = new Knapsack(items);

Alternatively, you could define a builder method to the Knapsack

public Knapsack(){
   // to do
}

public Knapsack withItem(String name, int amount) {
    Item i = new Item(name, amount);
    // to do: add to the Knapsack 
    return this;
} 

Then you would have

Knapsack k = new Knapsack().withItem("Pen", 15);

And you can chain multiple withItem calls together

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • yes this is exactly how to use this but then when is passed string and int I want in my new class use only that string and int separately. But it is in array right? so k[0] = pen and k[1] = 15 right? – marcellio Oct 20 '18 at 19:31
  • No, `k` is not an array, but let's assume it were, then `k.get(0)` would return an Item object, again, not an array, and you would do `k.get(0).getName()` – OneCricketeer Oct 20 '18 at 19:34