• Post Reply Bookmark Topic Watch Topic
  • New Topic

automation for new instances within object-instance  RSS feed

 
nimo frey
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have this:



Whenever a new Book-Instance is called, then it should automatically set a new Page-Instance (which is a property of Book):

Are these the only (good) ways:

version 1:




version 2:

 
Campbell Ritchie
Marshal
Posts: 56527
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Don't understand the question.
 
Wouter Oet
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I believe he is asking how to set instance variables when the object is constructed. The 2 methods you posted are good and the most used one's but you can also use an initialization block:

 
nimo frey
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I believe he is asking how to set instance variables when the object is constructed.


yes, this was my question, thanks.
I use this way:



}


And instantiate a new Book-Object (and implicitly a new Pages-Object):

Book b = new Book();

In the most cases, I do need a new Pages-Object when instantiating a new Book-Object.
However, what if I do not need a new Pages-Object in this case - is it a waste to create a new Instance without needing it?
Will it be garbage collected?

 
Wouter Oet
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you don't use it then it's a waste to create it. Especially if it's a big object. It won't be gc'ed because the holding object still has a visible reference. You could just not create it or use the Null Object Pattern
 
nimo frey
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
NullObjectPattern..so I have to provide a additional nullobject-class for each object.

I guess, it will be better to make this:



Or is there a better way?
 
Wouter Oet
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That is a good solution. You could also add another constructor with Pages parameter.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!