In a constructor designed to assign values ​​to class variables when creating an object, I sometimes use this. , sometimes not used. I checked - both options work, is one of them preferred?

public class Vehicle { private String color; Vehicle(String c) { color = c; } } 

 public class Vehicle { private String color; Vehicle(String c) { this.color = c; } } 
  • 3
    No, not necessarily. Mandatory only if the name of the parameter passed to the constructor matches the name of the class field. - Sergey
  • one
    In Java, in contrast to C (++), the auxiliary word this usually omitted (not used) if its use is not explicitly required (reference to the same-name class fields and local variables, for example) - pavlofff
  • THX. the actual question was asked. - Andrew Kachalin

2 answers 2

Optional, but allows not to invent names to the arguments of the constructor:

 public class Vehicle { private String color; Vehicle(String color) { this.color = color; } } 

    Preferably and, in principle, it would not work otherwise if the name of the argument coincides with the name of the class field:

     public class Vehicle { private Color color; Vehicle(Color color) { this.color = color; } } 

    In cases where the parameter name is different from the name of the field to which the value will be assigned - the word this optional. It will be implied.