Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

IntelliJ automatically adding "this" in front of member variables

When I create constructors in IntelliJ it automatically adds "this" in front of my member variables. Craig's version doesn't appear to do that. What does "this" mean, and should I change whether or not it's added to my variables?

2 Answers

Ken Alger
STAFF
Ken Alger
Treehouse Teacher

Alexander;

From the Java documentation:

Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.

Often times the this is bypassed by generating member variables with a prefix of m. Here are a couple of code samples to demonstrate the point.

samplePoint_1.java
public class Point {
    public int x = 0;
    public int y = 0;

    //constructor
    public Point(int a, int b) {
        x = a;
        y = b;
    }
}

We could also do:

samplePoint_2.java
public class Point {
    public int x = 0;
    public int y = 0;

    //constructor
    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

With the m prefix to designate member variables you would have:

prefixPoint.java
public class Point {
    public int mX = 0;
    public int mY = 0;

    //constructor
    public Point(int x, int y) {
        mX = x;
        mY = y;
    }
}

Those are all functionally the same. Post back with further questions and I'll dig through IntelliJ to show where you can alter it to generate the prefix.

Happy coding,
Ken

Ken Alger
Ken Alger
Treehouse Teacher

In IntelliJ... File, Settings, Editor, Code Style, Java and under Naming in the Code Generation tab you will see options for naming prefix and suffix. I have my naming prefix value to be m, for Member Variable as that is how it makes sense to me.

Crystal clear explanation. Thanks Ken!