When to use static methods

前端 未结 21 1920
旧巷少年郎
旧巷少年郎 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:41

    I am wondering when to use static methods?

    1. A common use for static methods is to access static fields.
    2. But you can have static methods, without referencing static variables. Helper methods without referring static variable can be found in some java classes like java.lang.Math

      public static int min(int a, int b) {
          return (a <= b) ? a : b;
      }
      
    3. The other use case, I can think of these methods combined with synchronized method is implementation of class level locking in multi threaded environment.

    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 instance object of the class. Does this mean I should use a static method?

    If you need to access method on an instance object of the class, your method should should be non static.

    Oracle documentation page provides more details.

    Not all combinations of instance and class variables and methods are allowed:

    1. Instance methods can access instance variables and instance methods directly.
    2. Instance methods can access class variables and class methods directly.
    3. Class methods can access class variables and class methods directly.
    4. Class methods cannot access instance variables or instance methods directly—they must use an object reference. Also, class methods cannot use the this keyword as there is no instance for this to refer to.

提交回复
热议问题