Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java Java Data Structures Getting There Class Review

Diego Marrs
Diego Marrs
8,243 Points

Can 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
Silviu Popovici
20,433 Points

A 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
Shae Ellis
8,151 Points

Also, 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.