Search code examples
javastaticinstance

Accessing an instance variable in main() method?


 class Test {
     Test obj;
     public static void main(String[] args) {
         obj = new Test();
     }
 }

I am aware of the fact that instance variable and non-static methods are not accessible in a static method as static method don't know about anything on heap.

i want to ask if main is a static method how can i access an instance variable 'obj'.


Solution

  • Why accessing an instance variable in static main is impossible: Instance variable of which instance would you expect to access?

    A possible misconception is that Java creates an instance of your main class when the application is started - that is not true. Java creates no such instance, you start in a static method, and it is up to you what instances of which classes you create.


    Ways out of this:

    • Declare Test obj as static

      static Test obj;
      public static void main(String[] args) {
          obj = new Test();
      }
      
    • Declare Test obj as local variable inside main

      public static void main(String[] args) {
          Test obj = new Test();
      }
      
    • Create an instance of Test in your main, then you'll be able to access its instance variables

      static Test obj;
      public static void main(String[] args) {
          obj = new Test();
          obj.myInstanceVariable = ... // access of instance variable
      }