leyren
leyren

Reputation: 534

Java Array in a constructor is not working

A strange thing happened to me which I am not able to explain to myself, so I hope someone can explain it to me. The situation is the following: I have an class called "Item". Instances of these class are instantiated with a name and two integer arrays, representing some values for this item (the meaning of these values are not important for this).

This works:

private Item item = new Item("Something", null, null);

This isn't:

private Item item = new Item("Something", {"A", "B"}, null);

This however works:

private String[] str = {"A", "B"};
private Item item = new Item("Something", str, null);

So.. my question is: Why? I absolutelty don't see why the second method isn't possible.

Upvotes: 1

Views: 58

Answers (1)

Reimeus
Reimeus

Reputation: 159864

The compiler doesnt automatically know the type of the array so it has to be expressly defined when declaring it as an expression

private Item item = new Item("Something", new String[] {"A", "B"}, null);

Upvotes: 2

Related Questions