So this code has an error because the base class has parameters right? Because the default constructor of each subclass calls the default constructor of the base class? and we don’t have a default constructor for the base class which causes the error?
Did I misunderstand it, also what is the best way around this while implementing the principle of code-reuse because I’m trying to practice programming in OOP
class A {
int item;
A(int item) {
this.item = item;
}
}
class B extends A {
int subitem;
B(int item) {
super(item);
subitem = item * 2;
}
}
class C extends A {
}
Firstly, on the title of this question:
Constructors are never inherited. It just doesn’t happen. What you’ve been demonstrating is not inheritance – it’s just the requirement that any constructor (other than the one in
java.lang.Object) has to either chain to another constructor in the same class, or chain to a constructor in the superclass.Well, to be precisely, it’s because the base class has no parameterless constructor.
A default constructor is only provided if you don’t specify any constructors explicitly. The default constructor always calls a parameterless constructor in the base class, implicitly.
We don’t have a parameterless constructor for the base class. Basically it’s equivalent to writing:
If you understand why that doesn’t compile, you understand why the version without any explicitly-declared constructors doesn’t compile, as they’re equivalent.
Around what? You can’t create an instance of
Awithout providing anitem. It would be bad if it did compile – what would theitembe? Every instance ofCcan also be considered to be anA, which requires anitem…You could write a parameterless constructor which provides some sort of default to the superclass constructor:
if that’s what you want. But beyond that, we can’t really suggest alternatives without knowing what you’re trying to achieve.
Note that inheritance is far from the only way of achieving code reuse – and in fact I personally prefer reuse via composition instead of inheritance in general. Inheritance is powerful, but overused IMO.