just a newbie here trying to understand inheritance. Here's what I've deduced so far portrayed in an example: Let's say we have 3 classes: Animal (superclass), Dog, and Cat. Classes Dog and Cat are inherited from Animal. Now let's say that in my main method, I declare 3 objects: Animal animal; Dog dog; Cat cat; It would be "legal" for me to do this: animal = dog; -Because I'm assigning "up" the hierarchy, correct? But doing this would be incorrect: dog = animal; -because here I'm assigning "down" the heirachy. But technically this would work if I casted: dog = (Dog) animal; Assuming that I'm stating all of this correctly (which is probably a big assumption), then here's what I don't understand: Since class Dog inherits class Animal, then it inherits all of the methods from class Animal, plus whatever new ones are defined in the Dog class. That being the case, then why won't dog = animal work? Dog already has whatever Animal has (plus more), so why can't it be assigned to reference an animal object? (without casting) Maybe I'm just visualizing this in the wrong way?? Thanks for any help!!
Post by:Bear Bibeault
That being the case, then why won't dog = animal work? Dog already has whatever Animal has (plus more), so why can't it be assigned to reference an animal object? (without casting)
You were fine up to this point. Imagine that the variable in animal points to a Cat instance. What happens when you call dog.bark()? hth, bear