"non-static variable cannot be referenced from a static context" is biggest nemesis of some one who has just
started programming and that too in Java. Since main method in java is most popular method among all beginners and
why main is declared static in Java see the link.
Why non static variable can not be called from static method
Now before finding answer of compiler error "non-static variable cannot be referenced from a static context", let's have a quick revision of static. Static variable in Java belongs to Class and its value remains same for all instance. static variable initialized when class is loaded into JVM on the other hand instance variable has different value for each instances and they get created when instance of an object is created either by using new() operator or using reflection like Class.newInstance(). 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 in my opinion only reason which make sense to disallow non static or instance variable inside static context is non existence of instance.
How to access non static variable inside static method or block
You can still access any non static variable inside any static method or block by creating an instance of class in Java
How to Convert String to Double in Java
How to Change Default pot of Tomcat
Ldap Authentication in Spring Security Tutorial and Example
How to Convert Date into mm/dd/yy format in Java
How to find current Date in Java with Example
Difference between fail-safe and fail-fast iterator in Java
No comments:
Post a Comment