When to use static methods

前端 未结 21 1911
旧巷少年郎
旧巷少年郎 2020-11-21 05:05

I am wondering when to use static methods? Say if I have a class with a few getters and setters, a method or two, and I want those methods only to be invokable on an instanc

相关标签:
21条回答
  • 2020-11-21 05:30

    Static methods are not associated with an instance, so they can not access any non-static fields in the class.

    You would use a static method if the method does not use any fields (or only static fields) of a class.

    If any non-static fields of a class are used you must use a non-static method.

    0 讨论(0)
  • 2020-11-21 05:31

    Static methods can be used if

    • One does not want to perform an action on an instance (utility methods)

      As mentioned in few of above answers in this post, converting miles to kilometers, or calculating temperature from Fahrenheit to Celsius and vice-versa. With these examples using static method, it does not need to instantiate whole new object in heap memory. Consider below

      1. new ABCClass(double farenheit).convertFarenheitToCelcium() 
      2. ABCClass.convertFarenheitToCelcium(double farenheit)
      

      the former creates a new class footprint for every method invoke, Performance, Practical. Examples are Math and Apache-Commons library StringUtils class below:

      Math.random()
      Math.sqrt(double)
      Math.min(int, int)
      StringUtils.isEmpty(String)
      StringUtils.isBlank(String)
      
    • One wants to use as a simple function. Inputs are explictly passed, and getting the result data as return value. Inheritence, object instanciation does not come into picture. Concise, Readable.

    NOTE: Few folks argue against testability of static methods, but static methods can be tested too! With jMockit, one can mock static methods. Testability. Example below:

    new MockUp<ClassName>() {
        @Mock
        public int doSomething(Input input1, Input input2){
            return returnValue;
        }
    };
    
    0 讨论(0)
  • 2020-11-21 05:33

    Static methods are the methods in Java that can be called without creating an object of class. It is belong to the class.

    We use static method when we no need to be invoked method using instance.

    0 讨论(0)
  • 2020-11-21 05:33

    In eclipse you can enable a warning which helps you detect potential static methods. (Above the highlighted line is another one I forgot to highlight)

    0 讨论(0)
  • 2020-11-21 05:35

    There are some valid reasons to use static methods:

    • Performance: if you want some code to be run, and don't want to instantiate an extra object to do so, shove it into a static method. The JVM also can optimize static methods a lot (I think I've once read James Gosling declaring that you don't need custom instructions in the JVM, since static methods will be just as fast, but couldn't find the source - thus it could be completely false). Yes, it is micro-optimization, and probably unneeded. And we programmers never do unneeded things just because they are cool, right?

    • Practicality: instead of calling new Util().method(arg), call Util.method(arg), or method(arg) with static imports. Easier, shorter.

    • Adding methods: you really wanted the class String to have a removeSpecialChars() instance method, but it's not there (and it shouldn't, since your project's special characters may be different from the other project's), and you can't add it (since Java is somewhat sane), so you create an utility class, and call removeSpecialChars(s) instead of s.removeSpecialChars(). Sweet.

    • Purity: taking some precautions, your static method will be a pure function, that is, the only thing it depends on is its parameters. Data in, data out. This is easier to read and debug, since you don't have inheritance quirks to worry about. You can do it with instance methods too, but the compiler will help you a little more with static methods (by not allowing references to instance attributes, overriding methods, etc.).

    You'll also have to create a static method if you want to make a singleton, but... don't. I mean, think twice.

    Now, more importantly, why you wouldn't want to create a static method? Basically, polymorphism goes out of the window. You'll not be able to override the method, nor declare it in an interface (pre-Java 8). It takes a lot of flexibility out from your design. Also, if you need state, you'll end up with lots of concurrency bugs and/or bottlenecks if you are not careful.

    0 讨论(0)
  • 2020-11-21 05:36

    Static methods and variables are controlled version of 'Global' functions and variables in Java. In which methods can be accessed as classname.methodName() or classInstanceName.methodName(), i.e. static methods and variables can be accessed using class name as well as instances of the class.

    Class can't be declared as static(because it makes no sense. if a class is declared public, it can be accessed from anywhere), inner classes can be declared static.

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