Java Reference
In-Depth Information
The statement in the derived class constructors that calls the base class constructor is:
super("Dog"); // Call the base constructor
The use of the
super
keyword here as the method name calls the constructor in the superclass - the
direct base class of the class
Dog
, which is the class
Animal
. This will initialize the
private
member
type
to
"Dog"
since this is the argument passed to the base constructor. The superclass constructor is
always called in this way, in the subclass, using the name
super
rather than the constructor name
Animal
. The keyword
super
has other uses in a derived class. We have already seen that we can
access a hidden member of the base class by qualifying the member name with
super
.
Calling the Base Class Constructor
You should always call an appropriate base class constructor from the constructors in your derived
class. The base class constructor call must be the first statement in the body of the derived class
constructor. If the first statement in a derived class constructor is not a call to a base class constructor,
the compiler will insert a call to the default base class constructor for you:
super(); // Call the default base constructor
Unfortunately, this can result in a compiler error, even though the offending statement was inserted
automatically. How does this come about?
When you define your own constructor in a class, as is the case for our class
Animal
, no default
constructor is created by the compiler. It assumes you are taking care of all the details of object
construction, including any requirement for a default constructor. If you have not defined your own
default constructor in a base class - that is, a constructor that has no parameters - when the compiler
inserts a call to the default constructor from your derived class contructor, you will get a message saying
that the constructor is not there.
Try It Out - Testing a Derived Class
We can try out our class
Dog
with the following code:
public class TestDerived {
public static void main(String[] args) {
Dog aDog = new Dog("Fido", "Chihuahua"); // Create a dog
Dog starDog = new Dog("Lassie"); // Create a Hollywood dog
System.out.println(aDog); // Let's hear about it
System.out.println(starDog); // and the star
}
}
Of course, the files containing the
Dog
and
Animal
class definition must be in the same directory as
TestDerived.java
. The example produces the rather uninformative output:
This is a Dog
This is a Dog