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 objstaticstatic test obj; public static void main(string[] args) { obj = new test(); }declare
test objlocal variable inside mainpublic static void main(string[] args) { test obj = new test(); }create instance of
testinmain, you'll able access instance variablesstatic test obj; public static void main(string[] args) { obj = new test(); obj.myinstancevariable = ... // access of instance variable }
Comments
Post a Comment