java - Accessing an instance variable in main() method? -


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

i aware of fact instance variable , non-static methods not accessible in static method static method don't know on heap.

i want ask if main static method how can access instance variable 'obj'.

why accessing instance variable in static main impossible: instance variable of which instance expect access?

a possible misconception java creates instance of main class when application started - not true. java creates no such instance, start in static method, , instances of classes create.


ways out of this:

  • declare test obj static

    static test obj; public static void main(string[] args) {     obj = new test(); } 
  • declare test obj local variable inside main

    public static void main(string[] args) {     test obj = new test(); } 
  • create instance of test in main, you'll able access instance variables

    static test obj; public static void main(string[] args) {     obj = new test();     obj.myinstancevariable = ... // access of instance variable } 

Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -