• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Difference instanciating object inside a constructor and outside the construcctor

 
Jacky Pepper
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there,

What is the difference between instanciating an object inside a constructor and outside the construcctor just in the class itself?

E.g. the difference between:

and:

In both ways there is a OtherClass instance-object available, isn't it? Is there a difference?
 
John Jai
Rancher
Posts: 1776
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Where you able to create an object using this structure? Replace the otherMethod(){} with a real method that will invoke the constructor and check what happens.




And welcome to the Ranch, Jacky Pepper
 
Winston Gutkowski
Bartender
Pie
Posts: 10508
64
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jacky Pepper wrote:In both ways there is a OtherClass instance-object available, isn't it? Is there a difference?

In effect: no. In flexibility: yes. The first style forces you to be able to construct the object from intrinsic data. With the second, you could pass runtime parameters to the constructor that allow you construct the object more dynamically. Note that this also applies if 'otherClass' is marked final.

Winston
 
Jacky Pepper
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks John and Winston!

... to be more clear, the examples should look like that:

and
 
Campbell Ritchie
Sheriff
Pie
Posts: 49797
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is another difference. If you don’t write your own constructor, the compiler will provide a default constructor. That might not be what you want.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic