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 trialdlpuxdzztg
8,243 PointsCan someone please explain?
4:00 Now, by creating these and not creating the setter, we've essentially made it impossible to change the object. And therefore, we achieved our goal of making it immutable.
I'm still confused by how doing this makes the variables immutable, why cant we just use 'final'?
Help is appreciated!
2 Answers
Silviu Popovici
20,433 PointsA setter method allows you to set the value of an object's private variable. So for example if we had a Car class that had a private string Model, the only way to change the value of Model of a Car object from outside the class would be to have a public method called setModel that changes the value. Then you would call setModel("Ford") or something like that from outside the class.
But if you simply don't make a public setter method for a private variable, then there's no way to change it from outside its class so it's considered immutable.
So in my example if setModel doesn't exist, then there's no way to change the object's Model variable from outside the Car class because Model is private.
Shae Ellis
8,151 PointsAlso, as an addition to what Silviu saidβand is spot on!βif I understand it correctly, you don't want to use the final modifier because that means whatever value is first assigned to those variables can never be changed, and it's not a variable that the user is to directly interact with.
I came across this article, and it explains the different kinds of modifiers and how you use them: http://www.studytonight.com/java/modifier-in-java.php
So, if you have a variable that will never be accessed by the user of a program, but just by the program itself, and you want the value of that variable to be permanent, then you use the final modifier.