java - Is it okay for a class to have a field of its own type -


i did following, got stackoverflow error after time, , understand why was.

public class cat {     string name="default name";     cat insidecat;      public cat(){          system.out.println("cat constructor");          insidecat = new cat();     }  } 

but if don't create new cat object within constructor, take parameter of cat type , assign insidecat field.

public class cat {     string name="default name";     cat insidecat;      public cat(cat insidecat){          system.out.println("cat constructor");          this.insidecat = insidecat;     }  } 

i playing around code, trying find out java can , cannot. in second code, looked normal, until started test class. need cat object create cat object (and create cat object need cat object...and goes on). technically cannot test class.

so question why java allow create instance variable of own type? guess whole purpose of constructor initialize it's instance variables. either have create new object initialize insidecat or else have take cat object outside. both doesn't seem work.

what missing here. there occurrence instance variables of own types can become useful, , can used without problem? bad oop practice come classes this?

classes exist time.

consider linked lists or trees, e.g.,

class listnode {   listnode next;   // etc. }  class treenode {   treenode left;   treenode right;   // etc. } 

you wouldn't initialize "child" objects in constructor, you'd add them later.

in example you'd need have method created insidecat @ later time. in general wouldn't create child objects had exact same state, there'd differentiate them either @ construction time, in case have "oh god stop creating these now" condition, or while being added, e.g., you'd add them via method , not in constructor.


Popular posts from this blog