NON-STATIC VARIABLE

"Instance Variables (Non-Static Fields)" Technically speaking, objects store their individual states in "non-static fields", that is, fields declared without the static keyword. Non-static fields are also known as "instance variables" because their values are unique to each instance of a class (to each object, in other words).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class HowToAccessStaticMethod
{
    int i;
    static int j;
    public static void staticMethod()
    {
        System.out.println("you can access a static method this way");
    }
    public void nonStaticMethod()
    {
        i = 100;
        j = 1000;
        System.out.println("Don't try to access a non static method");
    }
    public static void main(String[] args)
    {
        // i=100;
        j = 1000;
        // nonStaticMethod();
        staticMethod();
    }
}

This would produce following result:

-d option

The only way to call a non-static method from a static method is to have an instance of the class containing the non-static method. By definition, a non-static method is one that is called ON an instance of some class, whereas a static method belongs to the class itself.

Accessing non-static member variables from static methods (such as main)
Many programmers, particularly when first introduced to Java, have problems with accessing member variables from their main method. The method signature for main is marked static - meaning that we don't need to create an instance of the class to invoke the main method.
For example, a Java Virtual Machine (JVM) could call the class MyApplication like this :-
MyApplication.main ( command_line_args ); This means, however, that there isn't an instance of MyApplication - it doesn't have any member variables to access! Take for example the following application, which will generate a compiler error message.

1
2
3
4
5
6
7
8
9
10
11
public class NonStaticDemo
{
    public String my_member_variable = "somedata";
    public static void main(String args[])
    {
        NonStaticDemo demo = new NonStaticDemo();
        // Access member variable of demo
        System.out.println("This WON'T generate an error"
                + demo.my_member_variable);
    }
}

This would produce following result:

-d option