Why can non-static variable not be referenced from a static context?


  • 0
    S

    Why can non-static variable not be referenced from a static context?

    Solution:
    A static variable belongs to the class itself and can be accessed directly using the class name without the need of any instance(object) of the class.
    A non-static (aka instance) variable belongs to each object that is generated from that class and can be accessed through that object only.

    A non-static variable can't be accessed from a static method as the static method don't have access to a reference to any instance of the class. As static methods are tied to the class itself, it wouldn't know which instance of the variable to use, if any even existed at the time.

    Let's consider the following example.

    public class FooBar{
    
      private String foo = "foo";
      
      private void doFoo(){
         //Something
      }
      
      // main is a static method
      public static void main(String[] args)
      {
        //Error: Cannot make a static reference to the non-static field foo
        foo = "bar";
        //Error: Cannot make a static reference to the non-static method doFoo
        doFoo();
      }
    }
    

    In the source code above, an instance variable named foo and an instance method named doFoo has been created. These are referred to as instance variables and methods because you must create an instance of the FooBar class to instantiate and then use them.
    The main method is a static method and can be used without having an instance of the class but since it doesn't know about any instance(object) of the class, it can't reference the non-static variables foo and doFoo.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.