Question

I wanted to make a constructor that could pass arrays(not something I've done before/wasn't sure if even possible), so I wrote this:

class  Job {
    String name;
    int [] salary = new int[2]; // to represent a salary range
    static int jobCount=0;

    Job(String name,int[] salary){
        this.name=name;
        this.salary=salary; 
        jobCount++;
    }
}

but when I try and initialize it like so:

Job alpha = new Job("First",{20000,35000});

I get an 'illegal start of type' and indentifier expected errors. What am I doing wrong?

Was it helpful?

Solution

You need to use new int[] { } to declare the array inline:

Job alpha = new Job("First",new int[] {20000,35000});

OTHER TIPS

I slightly refactored your code:

class Job {
    String     name     = null;
    int[]      salary   = null;
    static int jobCount = 0;

    Job(String name, int... salary){
        this.name   = name;
        this.salary = salary; 
        jobCount++;
    }
}

public class Test {
    public static void main(String[] args) {
        new Job("abc", 1, 2, 3); 
    }
}
  1. If you want to pass a variable amount of arguments "by hand", it's not really necessary to use an array. Method which actually takes a variable amount of arguments is much more readable. Of course, if your code was just for testing purposes, this lose its sense and Luiggi's answer is absolutely correct.

  2. You don't really have to initialize field salary (and create a new instance of array) if you have only one constructor, which will initialize that field anyway. To understand what's happening there (simplified):

    • new instance is created
    • fields are initialized
    • code of constructor is executed

    Therefore, your initial value of field salary will get overwritten by constructor and you will lose its original value. It will be slow (allocation of memory is usually very slow) with no reason.

  3. I also don't understand purpose of jobCount field but it would be probably for a longer discussion.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top