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

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