File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Where to create objects Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Where to create objects" Watch "Where to create objects" New topic

Where to create objects

Dani Atrei
Ranch Hand

Joined: Feb 17, 2004
Posts: 73
I have a question about where to create objects, I m wondering whether it is better to create an class variable in instance, or to put the direct declaration in a method if the object is used by only one method of the class.
I m wondering about this because it might be more efficient to create a class variable (and hence an object of the class which method is called) in the single method interested in in using it.
Hope the question was clear, Daniel

Si altas son las torres, el valor es alto - Alberti
Gabriel White
Ranch Hand

Joined: Mar 02, 2003
Posts: 233
Dan, one of the points of Java programming is to efficiently utilize your system memory. Your point about instantiating objects in only the methods that require them is valid, however you have to look at the scope of the project. You may ask yourself, does this use up more memory if I declare the Object now or declare it in the main method? I usually try to only create "new" memory space when it is absolutely necessary. Soon you will learn about big O notation and omega and theta and little o for better memory usage. But for now, just stick to the formats that you are instructed with. You will soon see which is the best way to do it.
Billybob Marshall
Ranch Hand

Joined: Jan 27, 2004
Posts: 202
If, as you say, only one method needs the variable, and as long as the value does not need to persist between successive calls to that method, then yes definitely put it inside the method. That's better design, plus then you needn't worry about possible threading issues as well, as each thread invoking the method will get their own copy.
Gabriel White
Ranch Hand

Joined: Mar 02, 2003
Posts: 233
Yo, BB, sorry it got out of hand on the other page bro. I shouldn't have said anything. You are a great contributor to this forum.
You da man bro.
I agree. Here's the link:
subject: Where to create objects
jQuery in Action, 3rd edition