| Author |
Difference instanciating object inside a constructor and outside the construcctor
|
Jacky Pepper
Greenhorn
Joined: Jul 20, 2012
Posts: 2
|
|
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
Bartender
Joined: May 31, 2011
Posts: 1776
|
|
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
Joined: Mar 17, 2011
Posts: 4734
|
|
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
|
Isn't it funny how there's always time and money enough to do it WRONG?
|
 |
Jacky Pepper
Greenhorn
Joined: Jul 20, 2012
Posts: 2
|
|
Thanks John and Winston!
... to be more clear, the examples should look like that:
and
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32611
|
|
|
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.
|
 |
 |
|
|
subject: Difference instanciating object inside a constructor and outside the construcctor
|
|
|