Java Reference
In-Depth Information
private String type;
}
Directory "TestDerived"
This has a member, type , to identify the type of animal, and its value is set by the constructor. It is
private and is therefore not inherited in a class derived from Animal . You also have a toString() method
for the class to generate a string representation of an object of the class.
You can now define another class, based on the class Animal , to define dogs. You can do this immedi-
ately, without affecting the definition of the class Animal . You could write the basic definition of the class
Dog as:
public class Dog extends Animal {
// constructors for a Dog object
protected String name; // Name of a Dog
protected String breed; // Dog breed
}
You use the keyword extends in the definition of a subclass to identify the name of the direct superclass.
The class Dog inherits only the method toString() from the class Animal , because the private data mem-
ber and the constructor cannot be inherited. Of course, a Dog object has a type data member that needs to
be set to "Dog" ; it just can't be accessed by methods that you define in the Dog class. You have added two
new instance variables in the derived class. The name member holds the name of the particular dog, and the
breed member records the kind of dog it is. These are both protected and therefore are accessible in any
class derived from Dog . All you need to add is the means of creating Dog class objects.
Derived Class Constructors
You can define two constructors for the subclass Dog , one that just accepts an argument for the name of a
dog and another that accepts both a name and the breed of the Dog object. For any derived class object, you
need to make sure that the private base class member, type , is properly initialized. You do this by calling
a base class constructor from the derived class constructor:
public class Dog extends Animal {
public Dog(String aName) {
super("Dog");
// Call the base constructor
name = aName;
// Supplied name
breed = "Unknown";
// Default breed value
}
public Dog(String aName, String aBreed) {
super("Dog");
// Call the base constructor
name = aName;
// Supplied name
breed = aBreed;
// Supplied breed
Search WWH ::




Custom Search