aspose file tools*
The moose likes Beginning Java and the fly likes Basic Inheritance question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Basic Inheritance question" Watch "Basic Inheritance question" New topic
Author

Basic Inheritance question

Alex McCormick
Ranch Hand

Joined: Mar 08, 2003
Posts: 31
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!!
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61064
    
  66

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


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
 
 
subject: Basic Inheritance question