Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java "this" in constructors

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

like image 340
André Alçada Padez Avatar asked Nov 28 '25 20:11

André Alçada Padez


2 Answers

  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.
like image 120
wmorrell Avatar answered Nov 30 '25 10:11

wmorrell


  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.
like image 28
Kaleb Brasee Avatar answered Nov 30 '25 10:11

Kaleb Brasee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!