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:
- //Program of changing the common property of all objects(static field).
- class Student{
- int rollno;
- String name;
- static String college = "ITS";
- static void change(){
- college = "BBDIT";
- }
- Student(int r, String n){
- rollno = r;
- name = n;
- }
- void display (){System.out.println(rollno+" "+name+" "+college);}
- public static void main(String args[]){
- Student.change();
- Student s1 = new Student (111,"Karan");
- Student s2 = new Student (222,"Aryan");
- Student s3 = new Student (333,"Sonoo");
- s1.display();
- s2.display();
- s3.display();
- }
- }
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.
- class Counter{
- static int count=0;//will get memory only once and retain its value
- Counter(){
- count++;
- System.out.println(count);
- }
- public static void main(String args[]){
- Counter c1=new Counter();
- Counter c2=new Counter();
- Counter c3=new Counter();
- }}
Output:1 2 3
No comments:
Post a Comment