File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Where to create objects

 
Dani Atrei
Ranch Hand
Posts: 73
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi!
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
 
Gabriel White
Ranch Hand
Posts: 233
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 202
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 233
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
Gabe
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic