Java's implicit constructor invocation
I learned an interesting Java tidbit today that I’m surprised I never ran across before. It turns out that all object constructors implicitly call the superclass’ no argument constructor. Quoting from Section 8.8.5 of the Java Language Specification:
If a constructor body does not begin with an explicit constructor invocation and the constructor being declared is not part of the primordial classObject
, then the constructor body is implicitly assumed by the compiler to begin with a superclass constructor invocation "super();
", an invocation of the constructor of its direct superclass that takes no arguments.
This, in a sense, provides constructor inheritance, and ensures that some form of the parent’s constructor gets called be it explicitly or implicitly. For some reason I thought that a parent’s constructor was invoked only if called explicitly. I’m fairly certain this is the way C++ works. But now I will have to write a little test code to verify this. I actually like the implicit super()
behavior, and now that I know about it, I’m sure it’ll be useful at some point.