Varun
Varun

Reputation: 602

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'.

Upvotes: 4

Views: 11067

Answers (3)

Suhas
Suhas

Reputation: 31

Cannot access non-static variables inside a static method. So make obj as a static variable

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

Upvotes: 2

Jiri Tousek
Jiri Tousek

Reputation: 12440

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
    }
    

Upvotes: 4

Abdelhak
Abdelhak

Reputation: 8387

obj Should be static like this:

   static Test obj;

The main method does not have access to non-static members either.

Upvotes: 0

Related Questions