Java "this" in constructors

14,246

Solution 1

  1. Yes, it avoids the name clash. In the constructor's context, the name name refers to the parameter, and the name this.name refers to the instance field.
  2. Depends on what you mean by "better." Personally, I would make the name and number fields final, so the class is immutable. In my experience, it's better to start from an immutable class definition, and only move towards something mutable if there is a legitimate need to do so.

Solution 2

  1. Yes, this differentiates between an instance variable and a method parameter variable of the same name.
  2. There's always debate on whether constructor or setter initialization is better. If you're only going to set the name and number when you first create the object, and won't need to update those variables later, just using the constructor and leaving out the setters is probably better. And yes, in the setter, you'd need to use this if your parameter has the same name as the field you want to set.

Solution 3

There's no problem having the parameter using the same name as the field; the this. explicitly disambiguates and the program will behave as intended.

Depending on your program it may or may not be advantageous to use setters instead of directly writing fields. If you write the values directly in the constructor, then you bypass any runtime checks that you might have in your setters, which could potentially cause your object to hold data it normally can't. On the other hand, if your setter tries to do something with the old value, then you probably don't want to call the setter because, in the constructor, there might not be a meaningful old value. I'd say it's not clearly better or worse to set the fields in the constructor than to use setters, so long as you're careful to avoid breaking the class invariants.

Solution 4

  1. Yes. Using the this keyword avoids issues.

  2. If there are logic in the get/set methods, then you should use them instead. Otherwise, setting the values in the constructor is valid.

Solution 5

1) When the object scope property is the same as the argument name you must use this to differentiate between them. When there is a name clash the local var or argument will take precedence over the property.

For this reason, I don't like to ever have the exact same name for each as it can easily lead to bugs.

2) I also would use the setters from within the constructor, because if there ever needs to be a validation or some other operation done on the argument at time of setting you'll only have to make the change in one place. Otherwise it is duplication and violates the DRY (Don't Repeat Yourself) principle.

I would do:

public myClass (string name, int number) {
    setName( name );
    setNumber( number );
}
Share:
14,246
André Alçada Padez
Author by

André Alçada Padez

I'm a coder, a developer, mostly for web projects. I'm constantly eager to learn and master new technologies, and my day doesn't end when i punch out the clock. I obsess with code and algorithms. I dream about them and sometimes i wake up with a totally new approach for an impossible problem i've been having. I love my life and wouldn't dream of doing anything else.

Updated on July 18, 2022

Comments

  • André Alçada Padez
    André Alçada Padez almost 2 years

    Well, this is a very basic question, I've never coded in java, but I'm writing a class for a friend... Having something like:

    class myClass{
    
        private string name;
        public string getName() {
            return this.name;
        }   
        public void setName (int newValue) {
            this.name = newValue;
        }
    
        private int number;
        public int getNumber() {
            return this.number;
        }   
        public void setNumber (int newValue) {
            this.number = newValue;
        }
    }  
    

    The way I was thinking of building the constructor was:

    public myClass (string name, int numbers) {
        this.name = name;
        this.number = number;
    }
    

    My questions:

    1. I'm using the same identifiers for the properties as for the parameters. Does "this." avoid any trouble here?
    2. Is it better to use the set methods and, if so, should i use "this."?

    Thank you very much

  • Alb
    Alb over 13 years
    I really dislike the use of prefixes on fields. You shouldn't need to clutter the field name with what type or scope it is. I would go for your second approach.
  • winbina
    winbina over 13 years
    I agree. I was just mentioning the different styles that are common.