Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Creating objects in init() or class decleration?

 
Shay Gaghe
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
i have a biginner question for you guys
should i creates my objects in the declaretion point :
Vector v = new Vector();
or in the init() or constructor:
public void init(){
v = new Vector()
}
please expose why to use or not to use
thanks
 
jason adam
Chicken Farmer ()
Ranch Hand
Posts: 1932
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm not sure if personal preference, good design, or some other factor should sway you one way or the other. I think most often you want to create the object when it is needed, versus at the beginning of loading the class. In my classes that are composed of an object, I'll create the reference first, and then the object when it is time to use the object.
However, I've seen many examples of applets that just create all the objects first (the buttons, labels, etc.) and then use them as needed.
Jason
 
Geoffrey Falk
Ranch Hand
Posts: 171
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Usually I create things in the constructor. But sometimes there is a good reason to create things in init(). Especially when writing AWT code, I found that sometimes things are not initialized yet (for example, the graphics context) and so can't be used from within the constructor.
Also, I found that you can't start a thread from within a constructor.
Geoffrey
------------------
Sun Certified Programmer for the Java 2 Platform
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic