aspose file tools*
The moose likes Beginning Java and the fly likes Creating objects in init() or class decleration? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Creating objects in init() or class decleration?" Watch "Creating objects in init() or class decleration?" New topic
Author

Creating objects in init() or class decleration?

Shay Gaghe
Ranch Hand

Joined: Sep 03, 2001
Posts: 102
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

Joined: May 08, 2001
Posts: 1932
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

Joined: Aug 17, 2001
Posts: 171
    
    1
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


Sun Certified Programmer for the Java 2 Platform
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Creating objects in init() or class decleration?