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 Harnessing the Power of Objects Constants

Sumit Doshi
Sumit Doshi
388 Points

Can we use private int MAX_PEZ = 12;

Why we never used - private int MAX_PEZ = 12;

1 Answer

Erick R
Erick R
5,293 Points

Sure you can turn your variable into a private variable. However, if you turn it into private, the variable will only be accessible to the class it was defined to. You would have to add a set and get method to use this variable outside the scope of its class. In this video you learned what the static keyword does. It allows you to define the variable to be accessible at the class level. the final keyword means that it will not change and be constant. You can also declare a static variable as private, for example:

public class Pez(){
private static final int MAX_PEZ = 12;
//.................
//.............
//............

//To get this value and use it elsewhere i have to use a getter
public int getMaxPez(){
return MAX_PEZ;
 }

}

Remember that if you do it this way, the same rules apply. The variable will only be accessible at the Pez class level. If you try to change the public to private in your workspace, you will get an error because you are using it outside the scope of the class elsewhere. When you change it to private it no longer becomes accessible to other components in your code. It is always good to declare variables private but keep in mind that if you want to use it elsewhere you would have to change the keyword to public or use getters and setters to return this value for you.