We have faced an issue when writing a program, like "compiler error: non-static variable cannot be referenced from a static context".
public class TestProgram { int rollNumber; public static void main(String args[]) { rollNumber = 123; //compiler error: non-static variable count cannot be referenced from a static context } } Now, let we discuss the reason for above said error As we already know about Classes and Objects concepts, just remember below points- When a variable is declared as static, memory and value of that variable will be assigned at the time of class loading itself and static value will be shared across the instances and static block can be executed without an object.
- When a variable is declared as non-static, memory and value of that variable will be assigned at the time of object creation only.
Now look at the above code, inside main method we are trying to assign a value for rollNumber non-static member of TestProgram class. Suppose compiler is allowing to generate a byte code for above code, what will happen during execution? JVM doesn't knowing that,in which object value needs to be assigned, because we were not giving any object reference. Thats why compiler is not allowing to access a non-static variable from static block.
Non-static members can be accessed by static block with object reference only, so that JVM will come to know in object data needs to be modified
public class TestProgram { int rollNumber; public static void main(String args[]) { TestProgram obj = new TestProgram() obj.rollNumber = 123; } }Above code will not thrown any error, because we have created an object for TestProgram class and through that object reference only we are referring its member. I hope, this will help you to clear your doubt
No comments:
Post a Comment