I want to make diagrams that explain how Inheritance and Polymorphism work conceptually.
Assume that we have a Cat
class that inherits from the Animal
class. The way that I can think of a Cat
object is that it is an object that contains a copy of the members of the Cat
class and also it have an Animal
object inside of it.
Note: technically, I think that all Cat
objects share the same copy of the methods of the Cat
class, however, it is clearer to conceptually think of every Cat
object as if it contains its own copy of the methods of the Cat
class.
Now when we do:
Cat cat1 = new Cat();
Then cat1
will point to the Cat
object, this is how the diagram would look like:
The operations that are allowed on the cat1
variable are the following:
-
cat1.x
(will access thex
variable inside theCat
object). -
cat1.move()
(will call themove()
method inside theCat
object). -
cat1.jump()
(will call thejump()
method inside theAnimal
object).
And when we do:
Animal animal1 = cat1;
Then animal1
will point to the Animal
object that is inside the Cat
object, this is how the diagram would look like:
Note: the arrow pointing at the Animal
object doesn’t mean that animal1
actually point to a different location in memory than cat1
, the truth is that animal1
and cat1
point to the same location in memory, the arrow pointing at the Animal
object is just to indicate that animal1
can only access the members inside the Animal
object (unless we have an overridden method).
The operations that are allowed on the animal1
variable are the following:
-
animal1.x
(will access thex
variable inside theAnimal
object). -
animal1.move()
(now if themove()
method is not overridden in theCat
class, thenanimal1.move()
should call themove()
method inside theAnimal
object, however, since themove()
method is overridden in theCat
class, thenanimal1.move()
would call themove()
method inside theCat
object). -
animal1.jump()
(will call thejump()
method inside theAnimal
object).
Is my understanding correct?
Go to Source
Author: Tom