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

Jonas Schindler
Jonas Schindler
4,085 Points

Why declare the int "final" and not just "private"?

Hi Craig,

I understood that to prevent a variable from beeing accessed (including beeing changed) we use the modifier "private".

How does the "final" differ from that? Does it mean that this way the variable can still be accessed but just not changed?

Thanks a lot! :)

2 Answers

Axel McCode
Axel McCode
13,869 Points

Hi Jonas!

"final" is mainly used to prevent changes to a variable after it is initialized, making it a constant. Making a variable "private" will only allow it to be used in the class it was declared in. This helps with security. When we make a variable both "private" and "final" it cannot be changed and it cannot be accessed outside this class. Now, these private variables can be accessed outside the class through public methods, for example :

public class MyClass {

private final int num = 1;

public int getNum() {
    return num;
}

} 

In the code above the integer variable num is "final" so it is a constant and cannot be changed. num is also a "private" variable so the only way to access it out side MyClass is through public methods like the "getNum" method above. This technique of making the fields in a class private and providing access to the fields via public methods is called encapsulation, and I'm sure you'll be using it very often in the future.

Hope this helps :)

-Axel

Jonas Schindler
Jonas Schindler
4,085 Points

Hi Axel, thank you for your answer. Very well explained!