You have these two class definitions (or something equivalent).
abstract class Parent {
private int quality;
Parent(int quality) {
this.quality = quality;
}
}
abstract class Child extends Parent {
}
Let's first look at Parent
's constructor(s). There is only one, and it requires the caller to provide a quality
value. You explicitly don't provide a constructor that allows you to leave the quality
unspecified.
Now you have a Child
class that extends Parent
. Do don't specify any constructor, so Java's default applies, to silently create a dumb no-args constructor.
The Child
class extends its Parent
class, meaning that every Child
instance has all the properties of the Parent
, including the quality
. But when constructing a Child
, you didn't provide a way to specify what value to use for quality
.
In the Java inheritance system, a constructor must always start by initializing the parent class aspects of the instance, by calling a parent constructor, using the super(...)
syntax. If you don't write that call yourself, it's silently inserted into your constructor.
It's good practice and often necessary to write explicit constructors instead of relying on some dumb automatics. And in case of inheritance, a constructor should begin with a super(...)
call, specifying how to initialize the parent aspects of the instance to be created, in your case supplying a quality
value to the parent constructor.
So, depending on your requirements, a solution might be
abstract class Child extends Parent {
Child() {
super(42); // All Child instances get a constant quality=42
}
}
or
abstract class Child extends Parent {
// When cinstructing a Child instance,
// an explicit quality value must be supplied.
Child(int quality) {
super(quality);
}
}
After applying all built-in Java automatic code rules, your original version is equivalent to
// Auto: If you don't specify a parent class, it's java.lang.Object
abstract class Parent extends Object {
private int quality;
Parent(int quality) {
super(); // Auto: calls the `Object()` constructor to initialize
// aspects that every Java instance needs
this.quality = quality;
}
}
abstract class Child extends Parent {
// Auto: no constructor supplied in source, so a dumb one gets generated
Child() {
super(); // Auto: calls the parent's no-args constructor
// But there is no such constructor, hence compile error.
}
}