Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we use 'this' in setter method but not in getter method? [duplicate]

For example, in the following code:

private int id;

public void setID(int ID) {
    this.id = ID;
}

public void getID() {
    return id;
}

Why don't we say return this.id in the getter function or conversely say id = ID in the setter function? Also is this actually necessary? I mean, aren't the functions called through an object, say obj.setid(1) or obj.getid()? Will it work differently if I don't use the this keyword?

like image 552
Shreyas Yakhob Avatar asked May 08 '17 08:05

Shreyas Yakhob


1 Answers

You need to use this when the variable names are the same. It is to distinguish between them.

public void setID(int id) {
    this.id = id;
}

The following will still work when this is removed. It is because their names are not the same.

public void setID(int ID) {
    id = ID;
}
like image 173
Sky Avatar answered Oct 13 '22 00:10

Sky