HUNTER_X
HUNTER_X

Reputation: 13

Local variable and instance variable has the same name

I dont understand exactly the process that happened in this case:

class SomeClass {

    int val = 50;
    String str = "default";

 public SomeClass(int val) {
        val = val;
    }
}

what exactly happen in this statement val = val ?

Upvotes: 1

Views: 760

Answers (2)

Code-Apprentice
Code-Apprentice

Reputation: 83537

what exactly happen in this statement val = val ?

This assigns the value of the local variable val to itself. To assign the local val to the instance val, use the this keyword:

this.val = val;

Upvotes: 1

Abhijit Sarkar
Abhijit Sarkar

Reputation: 24558

The code, as shown, is wrong. The intent here is to assign the value of local variable val to the instance variable val. However, without a qualifier, this code just reassigns the local variable to itself. You’ll see it if you add a final to the constructor parameter. What you want is this.val = val. It’s common practice to name both the same for legibility, but qualify the instance variable with this. You also want a basic Java book.

Upvotes: 1

Related Questions