Can a Method access variables defined outside of its boundries? as i was experimenting with my very first java programs, i declared a variable outside of method Main which contained a print statement for that variable, and to my surprise i got an error message that says" cannot make a static reference to the non static field " what is that mean? and why does it work only when i declare my variable inside the method?
The reason is, non static variables must have initialized at the time of class loading, thus using non static variable in side a static method is not possible since non static variables dose not have existence before instantiation of the object for the containing class.
Static members are used do some kind of work with out even creating objects... Static members are class members .i.e. Single copy shared among all objects of the class. Whereas non static members are instance members and are object members.. Instance data members are unique identity of object.. Like ssn for an employee class... For each employee it is unique
Not even variables from the same class? Dare i ask what is a Static method? Why is there a need for an isolated method that cant use variables else where?
Since main is static it can not access the non static members of class.. If it was other non static function. You will not see that error