Sunday, August 10, 2014

Why main method is static

Why we generally keep main()  method in Java as static? 
Because an object is not required to call the static method. Also till java7 static blocks if defined before main were executed standalone before the main method.

let's take an example:

if you look at the code below, you will see that Student.change(); calls the change method defined in the constructor without any dependency on objects like s1, s2, s3 and that's the beauty of static keyword in context of methods:
  1. //Program of changing the common property of all objects(static field).  
  2.   
  3. class Student{  
  4.      int rollno;  
  5.      String name;  
  6.      static String college = "ITS";  
  7.        
  8.      static void change(){  
  9.      college = "BBDIT";  
  10.      }  
  11.   
  12.      Student(int r, String n){  
  13.      rollno = r;  
  14.      name = n;  
  15.      }  
  16.   
  17.      void display (){System.out.println(rollno+" "+name+" "+college);}  
  18.   
  19.     public static void main(String args[]){  
  20.     Student.change();  
  21.   
  22.     Student s1 = new Student (111,"Karan");  
  23.     Student s2 = new Student (222,"Aryan");  
  24.     Student s3 = new Student (333,"Sonoo");  
  25.   
  26.     s1.display();  
  27.     s2.display();  
  28.     s3.display();  
  29.     }  
  30. }  
Output:111 Karan BBDIT
       222 Aryan BBDIT
       333 Sonoo BBDIT

btw static variables are initialized only once and retains its values, a good example is as below, initially static variable count was = 0, when object c1 calls it, it increments to 1 and keep its value, if not defined static it would have lost its incremented value and when c2 object would have called the Counter constructor it would have received 1 again but because it is static and retains its value therefore on the next call of c2 it increments to 2 from 1 and 3 from 2 when c3 object calls the constructor.

  1. class Counter{  
  2. static int count=0;//will get memory only once and retain its value  
  3.   
  4. Counter(){  
  5. count++;  
  6. System.out.println(count);  
  7. }  
  8.   
  9. public static void main(String args[]){  
  10.   
  11. Counter c1=new Counter();  
  12. Counter c2=new Counter();  
  13. Counter c3=new Counter();  
  14.   
  15. }}  
Output:1
       2
       3

No comments:

Post a Comment