How to visualise Inheritance and Polymorphism?

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:

enter image description here

The operations that are allowed on the cat1 variable are the following:

  • cat1.x (will access the x variable inside the Cat object).

  • cat1.move() (will call the move() method inside the Cat object).

  • cat1.jump() (will call the jump() method inside the Animal 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:

enter image description here

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 the x variable inside the Animal object).

  • animal1.move() (now if the move() method is not overridden in the Cat class, then animal1.move() should call the move() method inside the Animal object, however, since the move() method is overridden in the Cat class, then animal1.move() would call the move() method inside the Cat object).

  • animal1.jump() (will call the jump() method inside the Animal object).

Is my understanding correct?

Go to Source
Author: Tom