Java Reference
In-Depth Information
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
}
}
Directory "TestDerived"
Of course, the files containing the Dog and Animal class definitions must be in the same directory as
TestDerived.java . I put them all in a folder with the name TestDerived . The example produces the
following rather uninformative output:
This is a Dog
This is a Dog
How It Works
Here you create two Dog objects and then output information about them using the println() method.
This implicitly calls the toString() method for each. You could try commenting out the call to super()
in the constructors of the derived class to see the effect of the compiler's efforts to call the default base
class constructor.
You have called the inherited method toString() successfully, but this knows only about the base class
data members. At least you know that the private member, type , is being set up properly. What you
really need though is a version of toString() for the derived class.
Overriding a Base Class Method
You can define a method in a derived class that has the same signature as a method in the base class. Having
the same signature means that the method names must be the same and the parameter lists must contain the
same number of parameters with identical types. The access attribute for the method in the derived class can
be the same as that in the base class or it can be less restrictive, but it cannot be more restrictive. This means
that if you declare a method as public in the base class, for example, any derived class definition of the
method must also be declared as public . You cannot omit the access attribute in the derived class in this
case, or specify it as private or protected .
When you define a new version of a base class method in this way, the derived class method is called for
a derived class object, not the method inherited from the base class. The method in the derived class over-
rides the method in the base class. The base class method is still there though, and it is still possible to call
it in a derived class. Let's see an overriding method in a derived class in action.
TRY IT OUT: Overriding a Base Class Method
You can add the definition of a new version of toString() to the definition of the derived class, Dog :
Search WWH ::




Custom Search