Menu
Topics Index
...
`


final, static and others >
Siva Nookala - 06 Oct 2016
As discussed in Creating Static Methods In Java Using Static Keyword, we can have static methods and variables in a class. We can also have non-static methods and variables. These are nothing but the normal member variables and methods. If a variable is not marked as static, then it is non-static variable or in other words it is a member variable. If a method is not marked as static, then it is a non-static method.

Please find few rules about the access rules between static and non-static methods and variables.
class A
{
    static int i_static = 0;
    int j_non_static;

    public static void printStatic()
    {
        System.out.println("i_static : " + i_static);

        // The below two statements causes compilation errors
        // System.out.println("j_non_static : " + j_non_static);
        // printNonStatic();
    }

    public void printNonStatic()
    {
        // All the three statements work fine.

        System.out.println("i_static : " + i_static);
        System.out.println("j_non_static : " + j_non_static);
        printStatic();
    }
}
Here we have defined a class A and created a variable i_static and a method printStatic as static and variable j_non_static and printNonStatic as non-static. The access rules are :
  • We can access a static variable from a static method. e.g., i_static is accessed from printStatic() method.
  • We CAN NOT access a non-static variable or non-static method from a static method. e.g., j_non_static and printNonStatic() can not be accessed from printStatic() method.
  • We can access a non-static variable from a non-static method. e.g., j_non_static can be accessed from printNonStatic() method.
  • We can also access a static variable or static method from a non-static method. e.g., i_static and printStatic() can be accessed from printNonStatic() method.
The below diagram pictorially shows why we can not access non-static variable from static context. Static-non-static-variables
Here we have one class A and 3 objects of the class, namely a1, a2 and a3. Since there is a separate copy of non-static variable for every object, we do not know which object's copy to use. So, when we call A.j_non_static, it does not know whether to use a1.j_non_static or a2.j_non_static or a3.j_non_static. But since i_static has only one copy and it is stored at the class level, either we access through class like A.i_static or through object using a1.i_static or a2.i_static or a3.i_static, all of them point to the same variable.

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.