Nutjob Joe
Nutjob Joe

Reputation: 11

Different ways to write getter and setter?

I have seen accessor methods using this and ones that don't. Do they produce the same results?

For example:

public setName(string name){
    this.name=name;
}

public setName(string n){
    name=n;
}

public void getName{
    return name;
}

public void getName{
    // is "this" here useless?
    return this.name;
}

What are the differences? Which way is better?

Upvotes: 1

Views: 98

Answers (3)

Pierpaolo Cira
Pierpaolo Cira

Reputation: 1477

It is the same. If your method has a variable with the same name of a class field (eg "name") you need to write "this.name" to refer to class field, because writing only "name" you are refering to method variable.

So in the second example you wrote, you have two different names ("name" and "n") and you don't need to write "this.name". By the way, in the second example, you are free to say "this.name" if you want, but it is not mandatory... (in my opinion it is not mandatory, but it is a great way to make your code more easy to read).

At the end choose what method you prefer. In my mind the first one is a more "elegant" way to write code.

Upvotes: 0

SamTebbs33
SamTebbs33

Reputation: 5647

Yes, they are entirely equivalent in their function and resulting bytecode (afaik).

The ’this’ keyword is only used when referencing an instance variable (a non-static variable that is defined with the class or relevant super-classes), in order to differentiate it from a local variable of the same name. Omitting the ’this’ keyword in such a situation would assign the local variable to itself.

Regarding your edit about what is better, some prefer not naming variables the same, but some like using ’this’ to explicitly refer to an instance variable. It comes down to a matter of taste and readability.

Upvotes: 0

Kon
Kon

Reputation: 10810

You need to use this when you want to reference the class level variable which has the same name as the local variable in the method. It is only required when the variables have the same name. You can always use this if you want, but it isn't necessary. And the difference between

this.s = s;

and

s = myString;

is just a style preference, and not a big important one that wars are fought over.

Upvotes: 1

Related Questions