Rushabha Jain
Rushabha Jain
Full Stack JavaScript Techdegree Student 11,140 Points

When 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
Trent Christofferson
17,644 Points

You 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.

Mohamed El-Damarawy
Mohamed El-Damarawy
10,334 Points

Well 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.