How do you ensure in Java that an object is created properly?
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.
Dig Deeper on Topics Archive
Have a question for an expert?
Please add a title for your question
Get answers from a TechTarget expert on whatever's puzzling you.