hi,
I will be briefing what a static variable/method/class/block means.
A static literally means stand still. In programming the implication is a variable/method/class/block which is complete in itself i.e. no instantiation is required for using the element.
A variable is complete in itself means that you don't need any object to acces the static field. There are shared by all the objects of the class and hence they can be accessed by the class name as shown below:
java
class test{
static int i = 0;
}
public class tester{
public static void main{
System.out.println(test.i);
}
}
But Sun thought that it would be nice to allow the static variables to be accessed by objects also. So a code example to show this is:
java
class test{
static int i = 0;
}
public class tester{
public static void main{
test t = new test();
System.out.println(t.i);
}
}
A code sample illustrate that the same copy of static variable is used among the objects of the class is as:
java
class test{
static int i = 0;
public test() {
i++;
}
}
public class tester{
public static void main{
test t1 = new test();
System.out.println(t1.i);
test t2 = new test();
System.out.println(t2.i);
}
}
The output of the above code will be
1 2
which proves that same static variable is used for all the objects of the class.
A method is complete in iteslf has the implication of a variable that it can be used without creating any instance of the class. Here is a code sample to illustrate this:
java
class test{
static int testMethod(){
System.out.println("tested static");
}
}
public class tester{
public static void main{
System.out.println(test.testMethod());
}
}
As in case of variables, the static methods can also be accessed by using the objects.
main is the most common example of a method being static.
Please note that a static method can't access non-static members of the class and main method is no exception to it.
A static class is complete in itself means that its memebers can be accessed without creating any instance of the class. Thus in effect all the members of the class become static.
Please note that a top-level class can't be declared as static. The discussion of top-level and inner classes is a big topic in itself and more info about static classes can be found
hereEven a code block can be static. But it has to be independent code block inside a class as shown below:
java
class test{
static int i=0;
static{
i++;
}
}
public class tester{
public static void main{
System.out.println(test.i);
}
}
The output will be 1 because the static block is executed while the class is being loaded by the JVM.