Can we access the instance variables from a static method in Java?


We cannot directly access the instance variables within a static method because a static method can only access static variables or static methods.

An instance variable, as the name suggests is tied to an instance of a class. Therefore, accessing it directly from a static method, which is not tied to any specific instance doesn't make sense. Therefore, to access an instance variable, we must have an instance of the class from which we access the instance variable.

Example:

public class Test {
   public int instanceVariable = 10;
      public static void main(String args[]) {
      Test test = new Test();
      System.out.println(test.instanceVariable);
   }
}

Output:

10

Updated on: 30-Jul-2019

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements