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?
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With