It's not a secret anymore!*
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
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: 7498
    
  18

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: 37925
    
  22
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.
 
Consider Paul's rocket mass heater.
 
subject: Difference instanciating object inside a constructor and outside the construcctor
 
Similar Threads
Where do class level reference variable get stored
Correct Inner Class....
Packages etc.
Why This Compiler Error?
Static vs non static