OOP: Polymorphism in Java

The ability of an object to take many forms.

Photo by Nitty Ditty on Unsplash

We can create polymorphic objects when we have a parent-child relationship between classes or interfaces and their implementations.

Let’s say we have these classes

Car class is parent class of BMW and Audi

We can create objects like this

So you can see how Car object can be BMW and Audi as well. That’s why we say the ability of an object to take many forms.

This part is a reference type. We always need to remember that reference type will decide what methods and properties available for the object.

This is the actual object part. If BMW or Audi classes override the methods from the Car class. During the runtime, the overridden method will get called.

The polymorphism with interfaces and abstract classes will work exactly the same.

and let’s create a BMW class.

and the way we use

  • car.drive(); will print BMW is driving because the BMW class overrides the parent method. This is also known as runtime polymorphism because java thinks it will execute the method of the Car class but during the runtime, it will figure out that BMW overrides it and will execute BMW’s method.
  • car.stop(); the output will be Car is stopping the parent class method will get called.
  • car.driveFast(); will compile because. The reference type decides what methods are available for car the object. And Car does not have driveFast(); method.

That’s it for polymorphism in Java. Have a nice day!

Software Developer, Java Instructor https://www.techleadacademy.io/