Alright so I’ve looked for documentation by googleing, however I haven’t found any that really describes what I’m looking to answer, so here I am asking you guys.
So I get inheritance, and how it works. What I’m having a problem with is sometimes I see a object originally defined as one type, and set to a different type, and I don’t understand exactly what’s happening. Here’s an example:
Say I have a class animal, and classes cat and dog which extend animal. Cat, animal and dog all have a method speak() which for cat prints “meow” and for dog prints “woof” and for animal “can’t speak”.
Alright so finally here’s my question. What exactly happens if a make a cat (c) and then run Animal a = c;? What happens if I run a.speak();? Which speak method is called? What exactly has happened when I change types like that? Will I ever have any real reason to use this?
As far as abstract methods go, my question is what exactly is the point of having them? In the examples I’ve seen they’ve been put in super classes and the classes under them define the exact behavior. By putting an abstract method in a super class is one requiring all the classes under it to implement it?
Thanks for all your help!
Always the method of the real class, for example in this case, the
speak()method of the cat.They make sure that, for example, every animal has a method
walk()that you can call on every animal. It’s a warranty that says “everyAnimalobject has this method, you don’t have to care about it”.To implement it or to be abstract, too, yes.