#334 – A Base Class Variable Can Refer to Instances of Derived Classes
May 27, 2011 3 Comments
A variable whose type is a particular class can refer to instances of that class or it can refer to instances of any derived classes.
Assume that we have a Dog class (base class) and a Terrier class (derived class) that inherits from Dog. A variable of type Dog can then refer to either a Dog or a Terrier.
Dog kirby = new Dog("Kirby", 15); // Dog variable can point to Terrier Dog jack = new Terrier("Jack", 17, "Surly"); // Terrier variable can also point to Terrier Terrier bubba = new Terrier("Bubba", 2, "Happy");
Notice that even though the variable jack is of type Dog, it still points to an instance of a Terrier.