Sunday 20 September 2015

Instance (non-static) variable cannot be called from static method


Compiler error: "non-static variable cannot be referenced from a static context".

Static variable in Java belongs to Class and its value remains same for all instances.

public class Test {
       int var = 0;
       public static void main(String args[] ) {
              ++var; // Cannot make a static reference to the non-static field count
       }
}

Initialization:

Static variable: class is loaded into JVM.

Instance variable: They get created when instance of an object is created either by using new() operator or using reflection like Class.newInstance() and has different value for each instances.

So if you try to access a non-static variable without any instance compiler will complain because those variables are not yet created and they don't have any existence until an instance is created and they are associated with any instance. So this may be the reason which makes sense to disallow non static or instance variable inside static context is non-existence of instance.

Since code in static context can be run even without creating any instance of class, it does not make sense asking value for a specific instance which is not yet created.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...