When should I use static methods in a class and what are the benefits?

前端 未结 10 1319
孤独总比滥情好
孤独总比滥情好 2020-11-27 12:34

I have concept of static variables but what are the benefits of static methods in a class. I have worked on some projects but I did not make a method static. Whenever I need

相关标签:
10条回答
  • 2020-11-27 13:09

    Your description of a static variable is more fitting to that found in C. The concept of a static variable in Object Oriented terms is conceptually different. I'm drawing from Java experience here. Static methods and fields are useful when they conceptually don't belong to an instance of something.

    Consider a Math class that contains some common values like Pi or e, and some useful functions like sin and cos. It really does not make sense to create separate instances to use this kind of functionality, thus they are better as statics:

    // This makes little sense
    Math m = new Math();
    float answer = m.sin(45);
    
    // This would make more sense
    float answer = Math.sin(45);
    

    In OO languages (again, from a Java perspective) functions, or better known as methods, cannot have static local variables. Only classes can have static members, which as I've said, resemble little compared to the idea of static in C.

    0 讨论(0)
  • 2020-11-27 13:10

    Static variable is used when you want to share some info between different objects of the class.As variable is shared each object can update it and the updated value be available for all other objects as well. As static variable can be shared,these are often called as class variable.

    0 讨论(0)
  • 2020-11-27 13:17

    Essentially, static methods let you write procedural code in an object oriented language. It lets you call methods without having to create an object first.

    0 讨论(0)
  • 2020-11-27 13:20

    Static methods don't pass a "this" pointer to an object, so they can't reference non-static variables or methods, but may consequently be more efficient at runtime (fewer parameters and no overhead to create and destroy an object).

    They can be used to group cohesive methods into a single class, or to act upon objects of their class, such as in the factory pattern.

    0 讨论(0)
提交回复
热议问题