[Java] I studied polymorphism, so I will summarize how to use it and its merits.

Introduction

From now on, I will post what I have learned to Qiita to improve my skills. This time about Java polymorphism. Since both Java and Qiita are beginners who are super-skilled, there may be mistakes. It would be helpful if you could tell me at that time.

Language and OS

This article uses Java 11.0.6 installed on Windows.

What is polymorphism?

It is a function that makes development easier by grasping an object roughly. For example, "roses," "sunflowers," and "tulips" are ** in detail **, although they are grown differently, they all have the same point that they bloom when water is given. Therefore, we have a ** rough way of thinking ** of these three types as "flowers", and if we know that they are "flowers", we will water them for the time being. It is ** polymorphism ** to try this way of thinking in a program.

Take advantage of polymorphism in your program

There is no special way to write it, just write the assignment.

Substitution is like this

Assignment.java


int num1 = 100;
int num2 = 200;
num1 = num2;

String str = "Polymorphism";

It's about putting variables and literals in variables.

When I actually write it, it looks like this.

Tataisei.java


Flower f2 = new Rose();

There is a class called Rose in the class type called Flower. In other words, there is a Rose instance in the Flower box. ** In detail, it's ** Rose, but ** roughly ** it's not considered as Flower.

The following is an example of poor use of polymorphism.

Tataisei.java


Flower f2 = new Doctor();
Rose f3 = new Flower();

Look at the first line first. It's strange that the Flower box contains a Doctor instance. The doctor is not a flower. For the second line of code, the class name has been reversed. It is said that this box contains Rose, and when I look at the contents, it looks like there is an abstract thing called Flower.

The trick to using polymorphism correctly is to see if it has an "is-a" relationship. Let's see if it is "class name of the created instance is a variable class name". In this case, "Rose is-a Flower" is the correct relationship.

What Happens When Using Polymorphism

Changes in callable methods

Polymorphism allowed us to get a rough idea of the instance. If you use this, each of the "rose", "sunflower", and "tulip" will be instructed (method) at 8 am, if water is given, it will be absorbed and flowers will bloom. ), But if you instruct one of the rough things called "flowers", the instances contained in it will ** play their respective roles **.

On the other hand, if you take it as a rough idea, the following problems will arise. Look at the two codes below.

Flower.java


public abstract class Flower {
    String name;
    String color;
    public void bloom() {
        System.out.println("this.name + "Is" + this.color + "Bloomed in color");
    }
}

Rose.java


public class Rose extends Flower {
    int thron;
    public void cutThorn() {
        System.out.println(this.name + "Thorns" + this.thron + "Cut into pieces");
    }

Rose is basically the same as the Flower class, but it has some thorns. Therefore, using extends as code, it inherits Flower, and its own characteristic thorns and methods for them are written. As an image, the type of box is Flower and it seems that Rose is in it. If you instantiate Rose, you should be able to use the cutThron () method, of course. Let's actually use it.

Main.java


Rose r = new Rose();
Flower f = r;
f.bloom();
f.cutThron();

… Actually, this code works fine up to the 3rd line, but a compile error occurs on the 4th line. It's strange that you should have created a Rose instance. ..

The cause of this is the first line using polymorphism. Because the computer only knows that there is a kind of flower in a box called ** Flower **. If you put it in a box, you can't see the contents.

In other words, since the Flower class originally has a bloom (); method, it can be determined from the computer that bloom () cannot be used for the time being because it is in a box called ** Flower. However, since we do not know the detailed contents of the box (type of flower), we cannot determine that the instance contained in the Flower box is a Rose instance ** that can use ** cutThron (). As a result, you get a compile error because you can't do something that isn't certain.

Benefits of using polymorphism

At this point, I think that the number of methods that can be used for polymorphism has decreased, making it inconvenient. However, polymorphism has advantages that go beyond this inconvenience. In this section, we will describe the benefits. The first is ** the code is cleaner when combined with an array **, and the second is ** each instance does its job with just one instruction **. Let's look at a concrete example. In the code below, consider that Rose, SunFlower, and Tulip inherit from Flower, and that Flower has a bloom () method.

Combine with an array

First, if you write the code without using polymorphism, it will be as follows.

Main.java


public class Main {
    poublic static void main(String[] args) {
        Rose r = new Rose();
        r.bloom();
        SunFlower s = new SunFlower();
        s.bloom();
        Tulip t = new Tulip;
        t.bloom();

And next is the code I wrote using polymorphism.

Main.java


public class Main {
    public static void main(String[] args) {
        Flower[] f = new Flower[3];
        f[0] = new Rose();
        f[1] = new SunFlower();
        f[2] = new Tulip();
        for (Flower fl : f) {
            fl.bloom();
        }
    }
}

... In this example, the number of lines does not change much and I do not get a clean impression, but lol, if the number of flower types increases or the number of methods I want to add increases in the future, the number of lines will increase steadily with the former writing method. I will. Also, having multiple variables can be difficult to manage. So, like the latter, by grouping instances such as Rose in a Flower array and roughly grasping them as a Flower, even if the number of flower types and methods increases in the future, you only need to add elements, so code You can write neatly.

Do the job for each instance, even if you take it roughly

Previously, the contents of bloom () were the same for all instances. However, in reality, each flower blooms differently. For example, in Rose, one stem branches many times and blooms multiple flowers, but in SunFlower, only one flower blooms on one stem. With that in mind, let's say you override bloom () for each instance. Normally, you have to write bloom () in Main.java for the number of instances. However, if we put it together in Flower due to polymorphism, we only need to command bloom () once **, and each instance will execute its own bloom (). This may be easier to understand if you look at the code. The command from here is only bloom () once, but when this is executed, the Rose instance will branch the stem and make multiple flowers bloom, and the Sun Flower instance will make only one large flower bloom without branching the stem. In addition, it has its own unique way of blooming.

Main.java


public class Main {
    public static void main(String[] args) {
        Flower[] f = new Flower[3];
        f[0] = new Rose();
        f[1] = new SunFlower();
        f[2] = new Tulip();
        for (Flower fl : f) {
            f1.bloom();
        }
    }
}

In other words, even if we roughly consider Rose and SunFlower as Flowers and give a command to "bloom!", Rose and SunFlower will bloom in their own unique way of blooming.

Summary

In a nutshell, "polymorphism" is a wonderful function that makes it easier for us humans on the commanding side **. Lol It's a difficult function that is hard to get into the head just by studying once, so I would like to write the code many times while being aware of "is-a" and the class type of the box. Also, I want to get used to Qiita quickly. Thank you for watching so far.

Recommended Posts

[Java] I studied polymorphism, so I will summarize how to use it and its merits.
[Easy-to-understand explanation! ] How to use Java polymorphism
[Java] How to use FileReader class and BufferedReader class
[Java] How to use Calendar class and Date class
I stumbled on the Java version in Android Studio, so I will summarize it
I passed Ruby Silver (June 2020), so I will summarize it.
[Java] [javaSliver] The interface and abstract classes are complicated, so I will summarize them.
[Java] How to use Map
[Java] How to use Map
How to use java Optional
How to use java class
[Java] How to use Optional ②
[Java] How to use removeAll ()
[Java] How to use string.format
How to use Java Map
How to use Java variables
[Java] How to use Optional ①
I tried to summarize the basics of kotlin and java
How to call and use API in Java (Spring Boot)
How to use StringBurrer and Arrays.toString.
How to use Java HttpClient (Get)
How to use EventBus3 and ThreadMode
How to use Java HttpClient (Post)
[Java] How to use join method
[Java] How to use static modifiers (What are static final and static import)
How to use equality and equality (how to use equals)
[Processing × Java] How to use variables
[Java] How to use LinkedHashMap class
[JavaFX] [Java8] How to use GridPane
How to use class methods [Java]
[Java] How to use List [ArrayList]
I tried to summarize the methods of Java String and StringBuilder
How to use classes in Java?
I tried to summarize Java learning (1)
I tested how to use Ruby's test / unit and rock-paper-scissors code.
I tried to summarize Java 8 now
[Processing × Java] How to use arrays
How to use Java lambda expressions
[Java] How to use Math class
How to use Java enum type
[Java beginner] I got a little deeper understanding of "It's time to use new", so make a note
I don't really understand the difference between swift Error and NSError, so I tried to summarize it myself.
I was curious about how to use Optional orElse () and orElseGet () properly.
[Java] Note how to use RecyclerView and implementation of animated swipe processing.
I will write 5 ways to implement Java Singleton and various advantages and disadvantages
Multilingual Locale in Java How to use Locale
How to use OrientJS and OrientDB together
[Java] How to use the File class
[Java] How to use the hasNext function
I tried to summarize Java lambda expressions
How to use submit method (Java Silver)
[Java] How to use the HashMap class
[Easy-to-understand explanation! ] How to use Java instance
[Java] How to use the toString () method
Studying how to use the constructor (java)
[Processing × Java] How to use the loop
[Java] How to output and write files!
How to set up and use kapt
How to use Java classes, definitions, import
[Java] [Maven3] Summary of how to use Maven3
[Processing × Java] How to use the class