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

Member variable!?

Should we use member variables like mSomething to create them, or do we go with this.Something, like shown in the new Java object course? Thanks

2 Answers

Hi

Don't confuse using this with declaring a member variable.

When you create a class, you may assign a member variable as in:

Class ABC {

private String mMyString;

}

no this is needed nor it should be used.

now in the constructor ... as in:

public ABC(String mMyString) {

this.mMyString = mMyString;

}

now when you create an object off the class as in:

ABC abc = new ABC ("hello there from abc");

ABC efg= new ABC ("hello there from efg");

you are passing "hello there from abc" to the constructor, then the abc instance of the ABC class will have a member variable mMyString and it will be assigned the value of "hello there from abc". Hence what [this] is doing: it says assign ""hello there from abc"" to mMyString that belongs to instance abc of the ABC class.

Same applies to ABC efg= new ABC ("hello there from efg");

you are passing "hello there from efg" to the constructor, then the efg instance of the ABC class will have a member variable mMyString and it will be assigned the value of "hello there from efg". Hence what [this] is doing: it says assign ""hello there from efg"" to mMyString that belongs to instance efg of the ABC class.

if this answers your question, please mark the question as answered.

Thank you

Ken Alger
STAFF
Ken Alger
Treehouse Teacher

Branko;

Have a look at a couple of similar responses I have previously posted:

Post back with further questions as this is an important concept to grasp and is not isolated to the Java programming language.

Ken