Why are constructors not inherited in java?
What you are talking about is Java language level. If constructors were inherited, that would make impossible to make class private. As we know method visibility can't be downgraded. Object
class has a no argument constructor and every class extends Object
, so in case of constructor inheritance every class would have a no argument constructor. That breaks OO principles.
Things are different on bytecode level. When object is created, two operators are called:
- new - allocates memory for object
- invokespecial - calls constructor on newly allocated piece of memory
We can modify bytecode so that memory is allocated for Child class and constructor is called from Parent class. In this case we can say that constructors are inherited. One notice if we don't turn off byte code verification, JVM will throw an exception while loading class. We can do this by adding -noverify
argument.
Conclusion:
- Constructors are not inherited on language level due to OO principles
- Constructors are inherited on bytecode level
In simple words, a constructor cannot be inherited, since in subclasses it has a different name (the name of the subclass).
class A {
A();
}
class B extends A{
B();
}
You can do only:
B b = new B(); // and not new A()
Methods, instead, are inherited with "the same name" and can be used.
As for the reason: It would not have much sense to inherit a constructor, since constructor of class A means creating an object of type A, and constructor of class B means creating an object of class B.
You can still use constructors from A inside B's implementation though:
class B extends A{
B() { super(); }
}