• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Initializing an object for reuse

 
Meghna Bhardwaj
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I have a question regarding reusing an object. I jave a simple pojo with 7 different String and Integer instance variables.

I am doing some manipulation where I populate this pojo and then add it to a list. At this point I can reuse this pojo by initializing all its fields, instead of jsut creating a new pojo. But I am confused as to how I can invoke the constructor of this pojo (where I am initializing all the instance variables) without usign teh new keyword which would actually create a new object?


The above initialization yields a compiler error? Am i doing this right? it seems simple enough?

Any help appreciated. Thanks!

Regards
 
Campbell Ritchie
Sheriff
Pie
Posts: 49823
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sounds like a beginners' question.

You can't invoke the constructor of an object, only create an object from a class by calling a constructor. You might be able to use set methods to alter all those fields, but what you are doing doesn't look like good object-oriented design to me.
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can't call a constructor. If you want to reinitialise your object you need to write a method to do the initialisation. You can then call this method both from your constructor and from the code when you need to reinitialise.

You do realise that your list only contains a reference to the object don't you ? So if you make any changes to the object, the object referred to by the list will also change (because they are one and the same thing).
[ January 16, 2008: Message edited by: Joanne Neal ]
 
Meghna Bhardwaj
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the replies, you are right. I see that all the items I added to my list are the same object. So I guess reusing the object will not work.... I need to create a new object everytime.

Thanks guys, once again great help.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic