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
Alex Johnson
6,067 PointsIntelliJ 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
Treehouse TeacherAlexander;
From the Java documentation:
Within an instance method or a constructor,
thisis 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 usingthis.
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.
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:
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:
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
Alex Johnson
6,067 PointsCrystal clear explanation. Thanks Ken!
Ken Alger
Treehouse TeacherKen Alger
Treehouse TeacherIn IntelliJ...
File, Settings, Editor, Code Style, Javaand under Naming in the Code Generation tab you will see options for naming prefix and suffix. I have my naming prefix value to bem, for Member Variable as that is how it makes sense to me.