简体   繁体   中英

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

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 } 

obj Should be static like this:

   static Test obj;

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

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM