Static
---------------
Mostly 2 Reason :
********************************************************************
1:Sometimes when you want single space storage.
2:And you want to share that
3:Generally class method i.e instance method we call on
Object Of that class.
But if you need that method isn't associated with object of
that class.
Means you want to call that method without creating Object
of that class.
********************************************************************
Example 1:
-----------
class Test{
int i;
Test(){
i++;
}
public static void main(String a[]){
Test t1=new Test();
Test t2=new Test();
Test t3=new Test();
System.out.println(i); //1
System.out.println(i); //1
System.out.println(i); //1
}
}
Example 2:
class Test{
int i;
static int count=0;
Test(){
i++;
count++;
}
public static void main(String a[]){
Test t1=new Test();
Test t2=new Test();
Test t3=new Test();
System.out.println(i); //1
System.out.println(i); //1
System.out.println(i); //1
System.out.println("Count"+Test.count); //3
}
}
-------------------------------------------------------------
Example 2:
class Bird{
String name;
static int count=0;
Bird(String name){
this.name=name;
count++;
}
}
class Test{
public static void main(String[] args) {
Bird b1=new Bird("Sparrow");
Bird b2=new Bird("Parrot");
Bird b3=new Bird("Piegon");
Bird b4=new Bird("Peacock");
Bird b5=new Bird("Koyal");
System.out.println(b5.count);
}
}
Comments
Post a Comment