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

Difference when using methods of an Instance

So while studying Java Objects iv'e encountered something pretty interesting and I thought I should consult with the community.

I've noticed that if you use the keyword 'static' in a variable it becomes a 'class-level' variable which means it could be used in a method without creating an instance of the object.

code example :

public static final int MAX_PEZ = 12; ----and then later in the main class--- PezDispenser.MAX_PEZ when using the printf function of the system.out

I also found out while coding that there is a different way of doing it by creating a constructor , and creating another instance of the PezDispenser which I found to be long and exhausting.

Finally! my question , which way is better to write I would like to get some answers coders who got a bit experience and if it's only a personal preference thing....

Thanks for everyone, sorry for the long question/example :)

2 Answers

Allan Clark
Allan Clark
10,810 Points

So it's a question of what the variable represents. In this case all the Pez Dispensers created will have the same max number of pez. In no cases will we have 2 dispensers with different max numbers and it should never be changed for an individual instance of the dispenser. That's why it is applied to the class as a whole, it is essentially a constant variable for all the classes.

Just like you are saying, since the number should be constant on all instances of the class, it wouldn't make much sense to be forced to create an instance just to check that number.

Hope this helped.

Helped a lot thanks a lot for you help and support