• Post Reply Bookmark Topic Watch Topic
  • New Topic

creating instance in class's instance field  RSS feed

 
lil Yaure
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi everyone

When I'm creating new classes if I want the instances to be available at the start I always use the "new" keyword in the constructor or in a init() method,
but I see many people create new instances when they are declaring variables.

e.g.


instead of

in the constructor

Anyone know if there are any difference in creating new instances in the class's instance field vs creating new instances in the constructor?
or which one is more recommended?

many thanks



 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One risk is writing instantiation code that tries to reference objects that are not yet created. So whenever possible, I consider it a good practice to instantiate objects at the point of definition. That way, these objects will be available to the constructor if needed.
 
Ireneusz Kordal
Ranch Hand
Posts: 423
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Joe Eruay wrote:hi everyone
Anyone know if there are any difference in creating new instances in the class's instance field vs creating new instances in the constructor?

In the constructor you can easily prepare and pass custom parameters to invocations of new instances.
This is difficult when creating in the class's instance field.
You can also catch and handle errors (exceptions) - this is impossible in the class's instance field.

 
lil Yaure
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks for the answers, never know about the exceptions
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!