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

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

    When you register, you'll begin receiving targeted emails from my team of award-winning writers. Our goal is to keep you informed on recent service-oriented architecture (SOA) and SOA-related topics such as integration, governance, Web services, Cloud and more.

    Hannah Smalltree, Editorial Director

    By submitting your registration information to SearchSOA.com you agree to receive email communications from TechTarget and TechTarget partners. We encourage you to read our Privacy Policy which contains important disclosures about how we collect and use your registration and other information. If you reside outside of the United States, by submitting this registration information you consent to having your personal data transferred to and processed in the United States. Your use of SearchSOA.com is governed by our Terms of Use. You may contact us at webmaster@TechTarget.com.

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