Gesticulations and Other Geekery » Initialization order in Java classes
Gesticulations and Other Geekery » Page 'Initialization order in Java classes'

Initialization order in Java classes

I just found a Java “got’cha” (there certainly are plenty aren’t there?).

When a Java object is constructed the super class constructor is called first. So far this makes sense. But this also applies to initializations that are written at the point of declaration like:

Object obj = null;

This is different then leaving out the = null in that obj is nulled after the superclass constructor runs. This is usually not a problem, but I have a situation where some of the initialization occurs in a method called from the superclass constructor (this is a dubiously good design I know). The result is that if the initialization method called from the superclass sets obj that change will be overwritten with null in the subclass constructor.

It took me several hour to find this problem. I’m going to be much more careful with calls to virtual functions in the constructor. It is considered bad form for a reason. Also this is one of the few times I have started to understand why the functional programming fan boys bash on object oriented programming. The OO methodology is flawed in a number of ways. That being said I think there is a place for it. It models the real world of things that can interact in a very nice way. I think that the actor model may turn out to be better, but that will take time.

Posted in Java, Programming Theory

Leave a comment