java - Why can't I instantiate and create Object without main method? ( Error)


my code:

(causes stack overflow error)

public class overloads {     string uniqueid;         overloads ov2=new overloads();      public static void main(string[] args) {         system.out.println("in main");     }      public void setuniqueid(string theid) {         // ii lots of validation code, , then:         uniqueid = theid;         system.out.println(uniqueid);     } } 

this code works fine:

public class overloads {     string uniqueid;         public static void main(string[] args) {           overloads ov2=new overloads();           system.out.println("in main");     }      public void setuniqueid(string theid) {         // ii lots of validation code, , then:         uniqueid = theid;         system.out.println(uniqueid);                } } 

the presence of main method not relevant here. scope in have declared variables, however, important.

have walked through happens in first version of code?

create new instance of overloads   -> ov2 = create new instance of overloads       -> ov2 = create new instance of overloads          -> ov2 = create new instance of overloads 

and on. variable ov2 in scope of class, initialized whenever instance of class instantiated. never terminate until run out of memory , stack overflow. run debugger clearer view.

the second version of code instantiates 1 instace of overloads, in scope of main method. creating 1 instance not lead newly created instance creating new instance , on..


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -