More about Java constructors

jdavidb on 2008-01-11T16:58:29

Last entry, I noted that I'd never noticed before that Java subclasses don't inherit constructors. Now I just learned one reason why I probably hadn't noticed this: Java classes with no constructors explicitly defined will have an empty default constructor supplied for them by the compiler. (A default constructor is a constructor with no arguments.)

I mentioned that previously I'd wondered what had gone wrong when a couple of classes I was compiling from the command-line suddenly started giving me errors, and that the problem was that I thought constructors were inherited. In this case, what had happened was that every class in the inheritance hierarchy (it was an experiment in subclassing, among other things) was relying on this implicitly-supplied default constructor. Then I think I gave one of the classes a constructor that took arguments, but one of its subclasses was relying on it having a default constructor, which went away. Oops. :)