2

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 thises 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.

Community
  • 1
  • 1
Nes370
  • 23
  • 6
  • 1
    `public class Character`. Wow buddy.. You might run into a lot of trouble with that *class name*. [here](https://docs.oracle.com/javase/7/docs/api/java/lang/Character.html) is another `Character` class defined in the jdk :P – TheLostMind Nov 17 '14 at 05:51
  • 1
    Why? Is it already a preset name for another? Ok then I'll modify it to something like `Charact` in my code. Thanks for the heads up, I've actually heard a little about that class before, just didn't think about when I was writing my class. – Nes370 Nov 17 '14 at 05:53
  • 2
    It's a good idea to use `this` when you are referring to instance fields, but in many cases it is *optional*. Also, `private String Name;`. *Please no*. That's totally against Java **naming** convention. – Elliott Frisch Nov 17 '14 at 05:55
  • 1
    I use `this` explicitly inside setter methods and constructors. I think this makes the code cleaner.. This is optional though.. And yes, there is a Character class defined by the Java language. You should probably change the name of you class. – TheLostMind Nov 17 '14 at 05:56
  • Ahh, yeah that's the general idea of what I was trying to get an answer. Are there many/any cases where it's necessary? – Nes370 Nov 17 '14 at 05:58
  • 1
    Invoking overridable methods from constructors is a very bad idea. You should simply use `this.name = name` in your constructor. And respect the Java naming conventions. Variables shouldn't start with an uppercase letter. – JB Nizet Nov 17 '14 at 05:58
  • 1
    So it is in good practice to make setters with `this`. – Nes370 Nov 17 '14 at 05:59
  • Oh, thanks for answering that one, I wasn't sure if it was malpractice or not to capitalize variables. – Nes370 Nov 17 '14 at 06:00
  • Thanks for the advice JB NIzet, I'll change my code to just initialize the variables rather than use the setters. – Nes370 Nov 17 '14 at 06:03

3 Answers3

4

I think you already have a grasp on what this is for. It is available when you need to be explicit about what you are referring to.

Here is a novel example. (Don't actually write a class like this. It just serves to show usage of this.)

class Outer {
    int value; /* #1 */

    class Inner {
        int value; /* #2 */

        void setInnerValue(int value /* #3 */) {
            //    #2      #3
            //   vvvvv   vvvvv
            this.value = value;
        }

        void setOuterValue(int value /* #4 */) {
            //          #1      #4
            //         vvvvv   vvvvv
            Outer.this.value = value;
        }
    }
}

If there is no need to qualify what you are referencing, then yes it is superfluous.

this is also used to invoke constructors in a chain.

class Example {
    Example() { this(1); }
    Example(int i) { }
}

am I breaking any normal naming conventions?

Yes, you are. Identifiers in Java start with a lowercase letter by convention (unless they are static final constants which are generally all uppercase). You should follow the convention.

Radiodef
  • 37,180
  • 14
  • 90
  • 125
  • Thanks for the answer; I've never heard of using a chain like you did with your `class Example`. I am not very practiced in the normal naming conventions yet, but I will do my best to remember to keep my variables lowercase from now on. – Nes370 Nov 17 '14 at 06:09
  • I really like how your first code block explains how `this` is used to call up a variable in many situations. It's Very helpful for me if I begin using nested classes. – Nes370 Nov 17 '14 at 06:26
1

calling the setter methods with a this, like in this.setVariable(variable) is usually superfluous, but good practise.

Declaring any variables with an uppercase letter is confusing for all other java programmers who might have to maintain your code. We adopt conventions for good reasons. It will confuse you too eventually, when all your variables look like classes, and you can't tell your static calls from instantiated.

this is implicitly this object.

Edit: above sentence changed from this class

CharlieS
  • 1,432
  • 1
  • 9
  • 10
  • Yes, I see you all are very much so stressing about keeping my code in proper shape. Not sure I understand "tell your static calls from instantiated" but I think I will eventually. Thanks for also mentioning an answer to my setter question. – Nes370 Nov 17 '14 at 06:13
  • 1
    *this is implicitly this class*: no. `this` is this **object**. – JB Nizet Nov 17 '14 at 06:13
  • Thanks for the clarification, I think I understand the concept. – Nes370 Nov 17 '14 at 06:21
  • agreed, was considering static methods where no object exists, forgetting that `this` is then not there! – CharlieS Nov 17 '14 at 06:49
  • Is it not still possible to call new objects in static classes, and `this` isn't used in the static classes, only in the object classes? Sorry that is one ugly compound question I asked.^ – Nes370 Nov 17 '14 at 06:56
  • @CharlieS I agree using keyword `this` _"is usually superfluous, but good practice"_. But could you provide some references (i.e., URLs) – javaPlease42 Feb 03 '15 at 19:30
0

It's handy to use this, because later you will have things like super. and if you don't use super there and don't use this you will end up with messy code.

Gilian Joosen
  • 486
  • 3
  • 21
  • 1
    We literally just learned about using supers and `extends` in my last class's lecture (Friday). I haven't tried using a superclass in my code, but I can theoretically see what you'd mean by my code appearing messy when I implement that. – Nes370 Nov 17 '14 at 06:16