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 trialRushabha Jain
Full Stack JavaScript Techdegree Student 11,141 PointsWhen to use Static Method?
I am bit confused like when can i use the static method in the programming and may be proper real world example will be helpful
2 Answers
Trent Christofferson
18,846 PointsYou should use static when:
- The code in the method is not dependent on instance creation and is not using any instance variable.
- A particular piece of code is to be shared by all the instance methods.
- The definition of the method should not be changed or overridden.
- You are writing utility classes which should not be changed.
https://www.tutorialspoint.com/When-to-use-static-methods-in-Java
Mohamed El-Damarawy
11,294 PointsWell in general static means it's out of the context of an object, so you usually use it for definitive functionality that doesn't depend on a state.
Like in Factory design pattern, instead of creating an object, you use a method from a static class that returns a new object for you.