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 Java Objects (Retired) Harnessing the Power of Objects Methods and Constants

Aditya Puri
Aditya Puri
1,080 Points

Why would you make variables private ?

Why would you make variables private?? Craig says because that would "prevent" people from changing them. But how can any user change your program code?

And after all isn't it much more efficient to access variables values just by writing their names rather than making methods to access them?

1 Answer

Deividas Strioga
Deividas Strioga
12,851 Points

Hey Aditya, theoretically, hackers could create new classes without changing yours, and change values effortlessly. If there was a very private data you would not want others to change, you simply keep it private and not provide setter method.

Just using get() method instead of accessing original value directly has no noticeable impact on performance.

Aditya Puri
Aditya Puri
1,080 Points

1) But how can a hacker change the source code of a game? Wouldn't that make his game version incompatible with the server version and wouldnt let him play? If he were in a singleplayer game and is trying to change the source code through the game directory then can't he just edit the WHOLE game code including the code in which the variable was declared?

2) Is including the keyword "get" in front of getter methods a naming convention or is it an essential part of the syntax?

3)How can a java tell the difference between a class field variable and a method? Both of them start in the same way which is- (public/private) (output datatype) (name) .