Ask the Expert

How do you ensure in Java that an object is created properly?

How do you ensure in Java that an object is created properly?

    Requires Free Membership to View

If the meaning of "properly" implies "properly constructed by the VM", you can assume that an object is ready for method invocation or field access as soon as the application execution returns from the object's constructor.

If the meaning of "properly" implies "free from developer bugs", this can only be determined by the degree of QA work completed by the builder of the class. Since Java allows exceptions to be thrown from a constructor, developers should, and usually do, throw exceptions as needed from constructors. This allows you to enclose the object construction code within a try/catch block and catch any errors or exceptions that occur.

Construction of a Java object defined by a class that extends a complex hierarchy of parent classes is an intricate process starting with the base class and continuing down through the inheritance chain. Therefore if you are attempting to make method calls inside of the constructor of a class you should make sure you know what you are doing. For example, if you attempt to call a method inside of the constructor of a class that has been extended by a subclass, and the subclass overrides the method, you will be invoking the method of the subclass. This is a dangerous practice since some of the fields of the subclass may not be initialized yet.

This was first published in January 2003

There are Comments. Add yours.

TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: