When to use static methods

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

    A static method is one type of method which doesn't need any object to be initialized for it to be called. Have you noticed static is used in the main function in Java? Program execution begins from there without an object being created.

    Consider the following example:

     class Languages 
     {
         public static void main(String[] args) 
         {
             display();
         }
    
         static void display() 
         {
             System.out.println("Java is my favorite programming language.");
         }
      }
    

提交回复
热议问题