Java: Constructors - super example
Example of class without parameterless constructor
/////////////////// class without a parameterless constructor.
// If any constructor is defined, the compiler doesn't
// automatically create a default parameterless constructor.
class Parent {
int _x;
Parent(int x) { // constructor
_x = x;
}
}
////////////////// class that must call super in constructor
class Child extends Parent {
int _y;
Child(int y) { // WRONG, needs explicit call to super.
super(0);
_y = y;
}
}
In the example above, there is no explicit call to a
constructor in the first line of constructor, so the
compiler will insert a call to the parameterless
constructor of the parent, but there is no parameterless
parent constructor! Therefore this produces a compilation error.
The problem can be fixed by changing the Child
class.
////////////////// class that must call super in constructor
class Child extends Parent {
int _y;
Child(int y) { // WRONG, needs explicit call to super.
_y = y;
}
}
Or the Parent
class can define a parameterless
constructor.
/////////////////// class without a parameterless constructor.
// If any constructor is defined, the compiler doesn't
// automatically create a default parameterless constructor.
class Parent {
int _x;
Parent(int x) { // constructor with parameter
_x = x;
}
Parent() { // constructor without parameters
_x = 0;
}
}
A better way to define the parameterless constructor is
to call the parameterized constructor so that any changes
that are made only have to be made in one constructor.
Parent() { // constructor without parameters
this(0);
}
}
Note that each of these constructors implicitly calls
the parameterless constructor for its parent class, etc,
until the Object
class is finally reached.