-1

I'm trying something like this:

class ms {
    ms(int[] a) {
        !! int[] a=new int[a.length];

        this.a=a;
    }
}

The IDE shows a.can't be resolved(in line ##), and duplicate local variable (in line !!). How to fix this? Basically I want the instance variable of class ms to have the same name as the parameter passed in the constructor.

Thanks

David
  • 208,112
  • 36
  • 198
  • 279
  • 1
    There is no good reason and also absolutely no need to force a variable name to be the same as anything other. Having said that, you can not influence the name of a variable programmatically. – Zabuzard Mar 02 '19 at 16:31
  • 1
    Therefore, also read [Assigning variables with dynamic names in Java](https://stackoverflow.com/questions/6729605/assigning-variables-with-dynamic-names-in-java). Which explains this in more detail. – Zabuzard Mar 02 '19 at 16:32

2 Answers2

3

I think this is what you want:

class ms {
    int[] a;

    ms(int[] a) {
        this.a = a;
    }
}
pseudobbs
  • 214
  • 1
  • 6
  • Thanks. Also, what would happen if i don't put this.a? I suppose if the instance variable of the class has the same name as the constructor parameter then if we don't do so, it wouldn't make any sense, but if the names are different would be fine if i don't write this.var=a, instead just, var=a; var being the instance variable of the class and a being the constructor parameter. –  Mar 02 '19 at 17:23
  • I believe Java looks to the innermost scope first, meaning without the 'this' keyword, it would assign the 'a' that you passed in to itself, essentially doing nothing. – pseudobbs Mar 03 '19 at 12:06
2

Your method has a variable declared in its parameters:

int[] a

And you're trying to declare another identical variable:

int[] a

Why? You don't need to re-declare something that you already have. Your class-level variable can have the same name as your local variable, but you can't have two local variables with the same name.

Just remove the duplicate local variable:

ms(int[] a) {
    this.a = a;
}
David
  • 208,112
  • 36
  • 198
  • 279
  • This "a", I'm referring to is the instance variable of the class, I just wished that it's name is the same as that of the constructor parameter. –  Mar 02 '19 at 17:23