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 trialDavid Milburn
812 PointsCan you explain how you could have altered the member variable before you changed it to private? Not sure how this works
Just as the title says I can't see how it would have changed the member variable before it was changed to private? How could you have altered this and why would it matter?
1 Answer
Derek Markman
16,291 PointsA way that Craig could have appeared to change the value of mCharacterName from the Example class would be:
PezDispenser.java
public class PezDispenser {
public String mCharacterName = "Yoda";
}
Example.java
public class Example {
public static void main(String[] args) {
System.out.println("We are making a new pez dispenser");
PezDispenser dispenser = new PezDispenser();
System.out.println("The pez dispenser is going to be: " + dispenser.mCharacterName);
dispenser.mCharacterName = "Batman"; // LINE 8
System.out.println("The pez dispenser is going to be: " + dispenser.mCharacterName);
}
}
Any code that prints out the value of mCharacterName, that comes after line 8 in the Example class, would appear as "Batman"
But since the String literal of "Yoda" is assigned to mCharacterName, that means any code that logs the value of mCharacterName to the screen before line 8 would still appear as "Yoda" because that's mCharacterName's assigned value in the PezDispenser class.
OUTPUT:
We are making a new pez dispenser
The pez dispenser is going to be: Yoda
The pez dispenser is going to be: Batman
Craig doesn't want the chance of this ever being a possibility, if we were to compile Example.java and inside of the PezDispenser class, mCharacterName was set to private, the Example class wouldn't compile.