Java Reference
In-Depth Information
protected String name; // Name of a Dog
protected String breed; // Dog breed
Directory "TestDerived"
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 initializes the private member type
to "Dog" because 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 base class constructor name Animal .
The super keyword has other uses in a derived class. You have already seen that you 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 inserts a
call to the default no-arg 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 auto-
matically. How does this come about?
When you define your own constructor in a class, as is the case for the Animal class, no default con-
structor 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 constructor, you get a message saying that the constructor is not there.
TRY IT OUT: Testing a Derived Class
You can try out the Dog class with the following code:
public class TestDerived {
public static void main(String[] args) {
Dog aDog = new Dog("Fido", "Chihuahua");
// Create a dog
Search WWH ::

Custom Search