Pages

Tuesday, 10 September 2013

Static in Java, Static Variables, Static Methods, Static Classes



Static in java  very important concept in interviews.  Let us see the story behind static variables and methods and classes in java classes….
Static Variables
1
2
3
4
5
6
7
8
9
10
public class MyStatic
{
    int var;
    static int var2;

    public static int methodStatic()
    {
      ------------
    }
}
Observe the above class having 2 variables, 1 is instance and other is static.  If we create multiple objects of  ‘MyStatic‘ class, always instance variables will be given separate space for storage, but static variable is common to all objects of MyStatic class, no separate space will be given to each object. Any java object belongs to MyStatic class can modify that static variable,  even there is no need of creating object of a class to modify the static variables, we can modify them by its class name directly.
All java instance methods can access these static variables, and always static variables will be initialized first and then instance variables.


Static Methods
Here also same concept, we can call all static methods of a java class by its class name some thing…..
MyStatic.methodStatic();
We no need to create object for MyStatic class, we can call directly just like above which is always good practice to do. In general we used these static methods to access static variables and hmm in practical we may touch these static methods in banking related applications (Account Creating Module) and even in almost all real time projects. All instance methods of a class can access these static methods, but static methods cannot access any instance types directly.
I mean all instance’ can access static, but static cannot access any instance types directly;)
Static Classes
Hope you know that we can create inner classes in java, in java only inner classes can declare as static and we used to call them as Nested classes.

No comments:

Post a Comment