When you define a subclass, it does not inherit constructors from the superclass. For anything other than the default superclass constructor, you need to explicitly call a superclass constructor in each subclass constructor. (That means, among other things, that if the base class does not have a default constructor, neither can any child class every child class constructor must explicitly call a superclass constructor—and no child class can have simply a compiler-generated default constructor. There's one exception to this; see [*] below.)
Inheriting constructors could cause all sorts of problems. Imagine something like this:
class Base {
private int mId;
public Base(int id) {
mId = id;
}
. . .
}
Now we want to derive a class that has a second attribute—a tag—that we want to ensure is never null
. So we write the following:
class Derived extends Base {
private Object mTag;
public Derived(Object tag, int id) {
super(id);
if (tag == null) {
throw new IllegalArgumentException("tag cannot be null");
}
mTag = tag;
}
. . .
}
Now imagine constructing an instance of Derived
like this:
Derived derived = new Derived(3);
If constructors were inherited, this would presumably be legal. What would it mean? For one thing, mTag
would be set to its default value of null
. There would be no way for Derived
to enforce the rule that all instances of Derived
must have a non-null tag.
At the cost of requiring a bit more typing, Java rules out inheriting constructors precisely to allow each class to fully control how its instances get created.
[*] There's one case where the compiler will automatically generate a non-default constructor. Consider the Base
class above and this code:
Base foo = new Base(3) {
. . . // some extended functionality
};
Now foo
is being initialized to an anonymous subclass of Base
. For ease of reference, let's call this subclass Base$Anon
. The compiler will generate code equivalent to:
class Base$Anon extends Base {
Base$Anon(int id) {
super(id);
}
. . . // some extended functionality
}
Base foo = new Base$Anon(3);
This is the only case where the compiler generates a non-default constructor if you don't specify any constructors of your own. In fact, the language syntax doesn't even let you declare a constructor for an anonymous class; you must rely on the compiler generating one for you.