Friday, September 12, 2014

Static Modifier

The keyword static can be used for classes, methods and variables. We can’t apply static keyword for the top level classes, but we can apply for inner classes.
For every object a separate copy of instance variables will be created, but in the case of static variables a single global copy will be created at class level and shared by all objects of that class.
Example:
public class StaticTest {
            int i = 10;
            static int j =20;
           
            public static void main (String args[]){
                        StaticTest st1 = new StaticTest();
                        st1.i = 100;
                        st1.j = 200;
                       
                        StaticTest st2 = new StaticTest();
                        st2.i = 1000;
                        st2.j = 2000;
                       
                        System.out.println(st1.i + " -------- " + st1.j);
            }
}
Output: 100 -------- 2000

1. Generally static variable are used for class level constants always associated with final modifier. Static methods are utility methods.

2. Non static variable cannot be reference from static context.
Example:
public class StaticTest {
            int i = 10;
           
            public static void main (String args[]){
                        System.out.println(i);
            }
}
It throws compile time exception saying non static variable i cannot be referenced from a static context.

Consider the following declaration:
1.      Int I = 10;
2.      Static int i = 10;
3.      public void m1() {  System.out.println(i); }
4.      public static void m1() { System.out.println(i); }
Which of the following are not allowed simultaneously in the same class.
a.      1 & 2 (correct) (Instance variables can be accessed from instance area)
b.      1 & 4 (wrong) (CE saying non static variable cannot referenced from static context)
c.       2 & 3 (correct) (Static variables can be accessed from anywhere)
d.      2 & 4 (correct) (Static variables can be accessed from anywhere)

3. Usually static methods are utility methods and we should provide complete implementation. But for abstract methods we are not allowed to provide implementation. Hence abstract and static combination is illegal for the methods.

4. We can overload static methods but we can’t override.

No comments:

Post a Comment