Java Reference
In-Depth Information
Object
at the root of the class hierarchy. Because a superclass constructor is always
invoked as the first statement of its subclass constructor, the body of the
Object
constructor always runs first, followed by the constructor of its subclass and on
down the class hierarchy to the class that is being instantiated.
Whenever a constructor is invoked, it can count on the fields
of its superclass to be initialized by the time the constructor
starts to run.
m
g
The default constructor
There is one missing piece in the previous description of constructor chaining. If a
constructor does not invoke a superclass constructor, Java does so implicitly. But
what if a class is declared without a constructor? In this case, Java implicitly adds a
constructor to the class. This default constructor does nothing but invoke the super‐
class constructor.
O
For example, if we don't declare a constructor for the
PlaneCircle
class, Java
implicitly inserts this constructor:
public
PlaneCircle
()
{
super
();
}
If the superclass,
Circle
, doesn't declare a no-argument constructor, the
super()
call in this automatically inserted default constructor for
PlaneCircle()
causes a
compilation error. In general, if a class does not define a no-argument constructor,
all its subclasses must define constructors that explicitly invoke the superclass con‐
structor with the necessary arguments.
If a class does not declare any constructors, it is given a no-argument constructor by
default. Classes declared
public
are given
public
constructors. All other classes are
given a default constructor that is declared without any visibility modifier: such a
constructor has default visibility. (The notion of visibility is explained later in this
chapter.)
If you are creating a
public
class that should not be publicly instantiated, you
should declare at least one non-
public
constructor to prevent the insertion of a
default
public
constructor. Classes that should never be instantiated (such as
java.lang.Math
or
java.lang.System
) should define a
private
constructor. Such
a constructor can never be invoked from outside of the class, but it prevents the
automatic insertion of the default constructor.
Hiding Superclass Fields
For the sake of example, imagine that our
PlaneCircle
class needs to know the dis‐
tance between the center of the circle and the origin (0,0). We can add another
instance field to hold this value:
public
double
r
;