Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
OOP Principles: Polymorphism | OOP
Java OOP
course content

Зміст курсу

Java OOP

Java OOP

1. How to Work With IDE?
2. OOP
3. Interface

bookOOP 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:

java

Main

java

Present😏

copy
1234567
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:

java

Transport

java

Airplane

copy
1234567
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.

1. Why do we need polymorphism in Java?
2. How does polymorphism complement inheritance?
3. What keyword is used to overload a method?
Why do we need polymorphism in Java?

Why do we need polymorphism in Java?

Виберіть правильну відповідь

How does polymorphism complement inheritance?

How does polymorphism complement inheritance?

Виберіть правильну відповідь

What keyword is used to overload a method?

What keyword is used to overload a method?

Виберіть правильну відповідь

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 2. Розділ 4
We're sorry to hear that something went wrong. What happened?
some-alt