Mastering Polymorphism and Inheritance in Java

Write Less. Do More. Customize Everything.

By now, you've created classes, objects, and methods. But in real-world software, code doesn’t exist in isolation — it evolves, extends, and adapts. That’s where inheritance and polymorphism come in. These are two pillars of object-oriented programming that help you:

Inheritance: Learning From the Past

Let’s say you’re modeling animals in a zoo:

Inheritance Example

Now, instead of rewriting everything for every animal, you can extend:

Inheritance Example 2

Now both Dog and Cat have the name field and can override speak(). Think of extends as a way of saying: “I am everything my parent is — plus my own stuff.”

Polymorphism: Many Forms, One Interface

Polymorphism means: same method name, different behaviors. You can treat all animals the same, even if they act differently:

Polymorphism Example

Even though a1 and a2 are declared as Animal, they behave like their true types. Java figures out what method to call at runtime, based on the object’s actual type.

Superclass and Subclass: The Chain of Command

When a subclass doesn’t override a method, it inherits the one from the superclass. You can also call the parent method explicitly:

Superclass Subclass Example

Use super to reference the parent class’s version.

Abstract Classes: Blueprints for Subclasses

An abstract class cannot be instantiated directly. It exists only to be inherited from.

Abstract Class Example 2
Abstract Class Example 3

If a class has any abstract methods, it must be abstract too.

Why All This Matters

Inheritance and polymorphism are how you design flexible systems. Example:

Alternatives and Utilities

Practice Time

Try this:

1. Create a base class called Vehicle with a method startEngine().
2. Create a Car and a Motorcycle that inherit from Vehicle.
3. Override startEngine() in each subclass with a different message.
4. Create an array of Vehicle, store both in it, and call startEngine() in a loop.

You'll see polymorphism in action.

What’s Next

You’ve seen the concepts — now let’s apply them. In the next chapter, we’ll model a real-world domain using classes, inheritance, and all the tools we’ve learned so far. Think library systems, users, items, and logic all in one cohesive design. Ready to architect like a pro? Let’s go.