For example, there is such a class:

public Account { int id; public Account(int id) { id = id; } } 

As you can see, the name of the class field is the same as the name of the constructor parameter.
What does id = id mean in this case? Is the value assigned to the field?

  • one
    Simply put, what is announced later hides what was declared before it. :) Therefore, the method parameter hides the class field of the same name, which is obviously assumed to have already been declared before the parameter is declared. - Vlad from Moscow

2 answers 2

No, the id parameter that was passed to the constructor will be assigned its value.

You can verify this by checking the id value after creating the object:

 public static void main(String[] args) { Account a = new Account(100); System.out.println(a.id); } 

It will display 0 , not 100 .

You can also see this if you make the transmitted parameter final :

 public Account(final int id) { id = id; } 

In this case, an error will occur during compilation:

java.lang.RuntimeException: Uncompilable source code - final parameter id may not be assigned

To assign a value to a class field in this case, use this.id :

 public Account(int id) { this.id = id; } 

    Need to write

     this.id = id; 

    to access the class variable. Otherwise, you assign the local variable to itself.