When to use static methods

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

    Static methods in java belong to the class (not an instance of it). They use no instance variables and will usually take input from the parameters, perform actions on it, then return some result. Instances methods are associated with objects and, as the name implies, can use instance variables.

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

    Static: Obj.someMethod

    Use static when you want to provide class level access to a method, i.e. where the method should be callable without an instance of the class.

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

    Static methods don't need to be invoked on the object and that is when you use it. Example: your Main() is a static and you don't create an object to call it.

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