I've been doing some research here and there on the internet, and I think I almost understand how the this
keyword operates. My question is: When is this
a necessary function?
I know that it is useful for distinguishing between an Object's private instance variable and another variable that it's being set to if they have the exact same name. Example:
public class SomeObject {
private int someNum;
public SomeObject() {}
public setSomeNum(int someNum) {
this.someNum = someNum;
}
}
I also learned from the second answer @using-the-keyword-this-in-java that it is used for accessing a "nested" class. Although I have yet to try this out, it appears to be a pretty cool idea.
How this question came to be about: I am writing a class
that defines game characters from a bunch of attributes:
public class Charact {
private String name;
// A ton of other private variables that represent character stats.
public Charact() {} // This one is for the main character.
public Charact(String name, /*All of the other variable parameters*/) { // This one is used for making NPCs.
this.name = name;
// Setting of all of the other variables.
}
public String getName() {return name;}
public void setName(String name) {this.name = name;}
// All of the other getter and setter methods.
}
So here's a few questions about my code (that are tangential to my initial question):
Is calling the setter methods with a this, like in this.setVariable(variable);
, superfluous because it would do the same thing as setVariable(variable);
?
I specifically declared all of my private instance variables with an uppercase letter, allowing me to avoid the use of this
in my setters. Is it alright for me to do so (am I breaking any normal naming conventions?) or should I have ought to use lowercase variable names and this
es in the setters?
Does using this
somehow help identify which instance of a class is being referred to, or is it already implicit to the computer, meaning that this
is not really needed?
Any answers that can offer some depth of elaboration would be very helpful, as I've only started making non-static classes this last week. Also, this is my first question, so I am sorry if it doesn't really seem to be asked in the right formatting.