When to use static methods

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

    If you apply static keyword with any method, it is known as static method.

    1. A static method belongs to the class rather than object of a class.
    2. A static method invoked without the need for creating an instance of a class.
    3. static method can access static data member and can change the value of it.
    4. A static method can be accessed just using the name of a class dot static name . . . example : Student9.change();
    5. If you want to use non-static fields of a class, you must use a non-static method.

    //Program of changing the common property of all objects(static field).

    class Student9{  
     int rollno;  
     String name;  
     static String college = "ITS";  
    
     static void change(){  
     college = "BBDIT";  
     }  
    
     Student9(int r, String n){  
     rollno = r;  
     name = n;  
     }  
    
     void display (){System.out.println(rollno+" "+name+" "+college);}  
    
    public static void main(String args[]){  
    Student9.change();  
    
    Student9 s1 = new Student9 (111,"Indian");  
    Student9 s2 = new Student9 (222,"American");  
    Student9 s3 = new Student9 (333,"China");  
    
    s1.display();  
    s2.display();  
    s3.display();  
    }  }
    

    O/P: 111 Indian BBDIT 222 American BBDIT 333 China BBDIT

提交回复
热议问题