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

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:

Main.java

Main.java

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:

Transport.java

Transport.java

Airplane.java

Airplane.java

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?

question mark

Why do we need polymorphism in Java?

正しい答えを選んでください

question mark

How does polymorphism complement inheritance?

正しい答えを選んでください

question mark

What keyword is used to overload a method?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 2.  4

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 2.  4
some-alt