[java] When to use static methods

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