Course Content
Java OOP
Java OOP
OOP Principles: Polymorphism
Polymorphism
Polymorphism is another principle of OOP. You have already encountered polymorphism when you overloaded and overridden methods. In general, this is the essence of polymorphism. But the definition of polymorphism can be a bit intimidating:
But in reality, it's much simpler than it seems. Polymorphism, in simple terms, can be divided into 2 parts:
- Method Overloading: what you learned in this chapter, but let's review.
Let's look at an example: we need to write a method that takes an int
parameter and returns a String
, as well as a method that does the same but with a long
parameter. Let's take a look at the code snippet:
Main
Present😏
public String doStuff(int parameter) { //... } public String doStuff(long parameter) { //... }
As you can see above, we've created 2 methods with the same name but can do different things. This is method overloading.
- Method Overriding:
You've encountered this topic before when you overridden the
toString
method in this chapter. But let's review it once again.
Let's look at a code snippet that will show us how we can override a method. We have a class called Airplane
that inherits from the Transport
class. And in the Transport
class, there's a method called move
which returns "This transport has started moving".
We need the airplane to "start flying" instead of "moving". To achieve this, we will override the move
method in the child class:
Transport
Airplane
public class Transport { // some fields public String move() { return "This transport has started moving"; } }
As you can see, we have overridden the method from the parent class in the child class as required.
In this way, polymorphism complements inheritance very well. Through polymorphism, we can conveniently and optimally extend our code, making it flexible.
Thanks for your feedback!