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

characterName vs pezCount

Hello, so I am taking the new Java Objects course, and I am in the second unit in the course. I noticed in the second video that Craig added

pezCount = 0;

but pezCount is a private int. Why does he have to use this. for character name which is also private, but not for pezCount? Thanks in advance!

1 Answer

Hi

Suppose you have a class as shown below (Pseudo code)

class Demo { private int num; private String str

  public Demo(int num, String str)
  {
       this.num = num;
       this str = str;
  }

}

As you see, the constructor is being used to initialize the private class attributes.

this here is referring to the instances of the objects you created when you said

Demo demo1 = new Demo(123, "ABC"); Demo demo2 = new Demo(456, "DEF"); Demo demo3 = new Demo(789, "XYZ");

when you created the demo1 instance and hit hit the class constructor, this is now referring to demo1 when you created the demo2 instance and hit hit the class constructor, this is now referring to demo2 when you created the demo3 instance and hit hit the class constructor, this is now referring to demo3

Generally speaking this is not requerd, but it adds clarity when the argument has same name as the class attrinute as in

the method argument [int num] happens to have same variable name as [private int num;]

the compiler is smart enough to differentiate between the two ... but again doing so and adding this. helps with readability.

going back to pezCount = 0;

There is no reason to use this here ... this is a simple assignment.

If this helps answer you question, please mark the question as answered.