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 mainpublic static void main(string[] args) { test obj = new test(); }
create instance of
test
inmain
, 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