Java Reference
In-Depth Information
The base members are all there in a derived class object — you just can't access some of them in the
methods that you have defined for the derived class. The fact that you can't access some of the base class
members does not mean that they are just excess baggage — they are essential members of your derived
class objects. A Spaniel object needs all the Dog attributes that make it a Dog object, even though some of
these may not be accessible to the Spaniel methods. Of course, the base class methods that are inherited in
a derived class can access all the base class members, including those that are not inherited.
Though the base class constructors are not inherited in your derived class, you can still call them to ini-
tialize the base class members. More than that, if you don't call a base class constructor from your derived
class constructor, the compiler tries to arrange to do it for you. The reasoning behind this is that because a
derived class object has a base class object inside it, a good way to initialize the base part of a derived class
object is using a base class constructor.
To understand this better, let's take a look at how it works in practice.
Deriving a Class
Let's take a simple example. Suppose you have defined a class to represent an animal as follows:
public class Animal {
public Animal(String aType) {
type = new String(aType);
}
public String toString() {
return "This is a " + type;
}
Search WWH ::




Custom Search