Constructors Used in Inheritance Hierarchies
Syntax and Signature
A java constructor
has the same name as the name of the class to
which it belongs. Constructor’s syntax does not
include a return type, since constructors never
return a value.
Constructors may include parameters of various types.
When the constructor is invoked using the new
operator, the types must match those that are specified in the constructor
definition.
Calling
When you create an object of a class you
automatically call the constructor. The one called depends upon the
signature provided.
Overloading
Like
methods, constructors can also be overloaded. Since the constructors in a
class all have the same name as the class, their signatures are
differentiated by their parameter lists.
super Keyword
Every constructor calls its superclass constructor.
An implied super() is therefore included in each constructor which does not
include an explicit super() call as its first statement. The super()
statement invokes a constructor of the super class.
The
implicit super() can be replaced by an explicit super(). The super statement
must be the first statement of the constructor.
The
explicit super allows parameter values to be passed to the constructor of
its superclass and must have matching parameter types A super() call in the
constructor of a subclass will result in the call of the relevant
constructor from the superclass, based on the signature of the call.
Default Constructor
Java provides a default constructor which takes no
arguments and performs no special actions or initializations, when no
explicit constructors are provided.
The
only action taken by the implicit default constructor is to call the
superclass constructor using the super() call. Constructor arguments provide
you with a way to provide parameters for the initialization of an object.
You don't have to provide any constructors for your
class, but you must be careful when doing this. The compiler automatically
provides a no-argument, default constructor for any class without
constructors.
This default constructor will call the no-argument
constructor of the superclass. In this situation, the compiler will complain
if the superclass doesn't have a no-argument constructor so you must verify
that it does.
If your class has no explicit superclass, then it has an implicit superclass
of
Object,
which does have a no-argument constructor. The constructor of the
Object class performs no actions.