Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using "this" in setters

Tags:

java

I see no real difference between the following two methods of creating a setter, but was wondering if I am just naive. Is one more desirable than the other?

public void fooSetter(String bar)
{
    _bar = bar;
}


public void fooSetter(String bar)
{
    this._bar = bar;
}
like image 705
Chuck Wolber Avatar asked Aug 11 '10 17:08

Chuck Wolber


People also ask

Why do we use this in setter Java?

When you have define a class and an object of that class,you need this to initialize in setter if the passed argument name and the attribute name of the object are same. Basically this refers to the object through which the call is made.

Do setters have parameters?

The setter method takes a parameter and assigns it to the attribute. Getters and setters allow control over the values. You may validate the given value in the setter before actually setting the value.

What can I use instead of getters and setters?

You may use lombok - to manually avoid getter and setter method. But it create by itself. The using of lombok significantly reduces a lot number of code.

Can a setter have a return type?

Setters cannot return values. While returning a value from a setter does not produce an error, the returned value is being ignored. Therefore, returning a value from a setter is either unnecessary or a possible error, since the returned value cannot be used.


3 Answers

There is no semantic difference in this case because there is no ambiguity. If, on the other hand, your instance field was also called bar then this would be required to disambiguate:

public void fooSetter(String bar)
{
    this.bar = bar;
}
like image 60
Kent Boogaart Avatar answered Sep 25 '22 20:09

Kent Boogaart


You do not need "this" since there is no ambiguity. ("bar" and "_bar" are different. now if your field was called "bar" as well, you'd need it)

like image 39
Kirk Woll Avatar answered Sep 25 '22 20:09

Kirk Woll


The different styles are mostly caused by what a programmer did before Java, what coding standards are present in the company, etc.

The desired style is to use:

    public class A {
          private Type property;

          public Type getProperty(){
              return this.property;
          }

          public void setProperty(Type property){
              this.property = property;
          }
    }

This is kind of the best-practice style and complies to the JavaBeans standard.

like image 38
Johannes Wachter Avatar answered Sep 26 '22 20:09

Johannes Wachter