When to use static methods

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

    Whenever you do not want to create an object to call a method in your code just declare that method as static. Since the static method does not need an instance to be called with but the catch here is not all static methods are called by JVM automatically. This privilege is enjoyed only by the main() "public static void main[String... args]" method in java because at Runtime this is the method Signature public "static" void main[] sought by JVM as an entry point to start execution of the code.

    Example:

    public class Demo
    {
       public static void main(String... args) 
       {
          Demo d = new Demo();
    
          System.out.println("This static method is executed by JVM");
    
         //Now to call the static method Displ() you can use the below methods:
               Displ(); //By method name itself    
          Demo.Displ(); //By using class name//Recommended
             d.Displ(); //By using instance //Not recommended
       }
    
       public static void Displ()
       {
          System.out.println("This static method needs to be called explicitly");
       }
    } 
    

    Output:- This static method is executed by JVM This static method needs to be called explicitly This static method needs to be called explicitly This static method needs to be called explicitly

提交回复
热议问题