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 trialadsdev
15,583 PointsExplanation please :(
I have a question about some parts of the code. I finished it and all correctly but i don't entirely understand the thought behind it. The color variable is private, so i can assume that is only visible to the GoKart class and instances of it (objects right ?). Furthermore I have a headache about this xP :
If I use the getColor method in another object from another class, is this possible or not because of the private visibility ? Does it have to become a package or something ?
public class GoKart {
private String mColor = "red";
public String getColor(){
return mColor;
}
}
1 Answer
Jon Kussmann
Courses Plus Student 7,254 PointsLet's see if this helps:
You are correct in saying that a private variable can only be accessed within the class that it is defined (in this case mColor). This is why you CAN use it in the method getColor().
Now, if you had a different class such as... a Track class and you instantiate a new GoKart:
GoKart goKart = new goKart();
You cannot get the color through
goKart.mColor;
since mColor is private.
You can however use
goKart.getColor();
since that method is public. The fact that the getColor() method "uses" mColor does not matter because that is being run "within" the GoKart class, and not the Track class.
adsdev
15,583 Pointsjust for verification, because i get the rest, if i would be in the Track class, i would need to use the goKart.getColor() method to reach the mColor variable of the GoKart Class right ?
Jon Kussmann
Courses Plus Student 7,254 PointsYes, that is correct.
adsdev
15,583 PointsAlright, thanks a lot :D !
Joseph Nickalo
432 PointsJoseph Nickalo
432 PointsIยดm on this lesson and I can already tell that I will be going through hell lol. x_x