DEV Community

Geremi Wanga
Geremi Wanga

Posted on

Polymorphism

In the last post we talked about encapsulation today we are getting into polymorphism.

An analogy

so we have our houses right. We have a stone house, a brick house, a beach house. They are all houses. But if you asked each one to describe itself, each one would describe itself differently.

The beach house mentions the deck, the brick house mentions the bricks, the stone house mentions the stone.

Same question, different answers. That's polymorphism.
The word itself just means many forms. In Java the same method can behave differently depending on which object is calling it

We can have a describe method on the parent house class and every child class can override it to describe itself in its own way.

You call the same method, you get different results based on what you're actually dealing with.

But why

imagine you have a whole neighbourhood of different houses and you want each one to describe itself. Without polymorphism you'd have to know exactly what type of house each one is and handle each separately.

With polymorphism you just say describe yourself and each house handles it on its own terms. Your code stays clean, you don't have to think about every possible case.
It all connects

This is where everything we've covered starts clicking together. You have a parent class, child classes inheriting from it, fields locked down through encapsulation, and now methods that behave differently depending on who's calling them.

These aren't separate ideas, they're all working together.
The more i go through Java the more i realize these concepts aren't things you just learn and move on from.

They keep showing up together, building on each other, which honestly makes them easier to remember the further in you get.

At this point Java is just becoming my second language

Top comments (0)