wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Difference instanciating object inside a constructor and outside the construcctor Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Difference instanciating object inside a constructor and outside the construcctor" Watch "Difference instanciating object inside a constructor and outside the construcctor" New topic
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: 8016
    
  22

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?
Articles by Winston can be found here
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: 39436
    
  28
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.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Difference instanciating object inside a constructor and outside the construcctor