Java: polymorphism is the source of happiness

< H3 class = "heading" > 01 what is polymorphism

In my stereotype, the wonderful battle between monkey king and Erlang God in journey to the west can well explain the word "polymorphism": a monkey king can change 72; One Erlang God can also change seventy-two; They can all become different forms, but they just need to shout "change" quietly.

What is polymorphism in Java? In fact, it is a kind of ability - the same behavior has different forms of expression; In other words, by executing a piece of code, Java can produce different results according to different objects at runtime. Sun Wukong and Erlang God only need to shout "change", and then they change, and they become different every time; One truth.

There are three prerequisites for polymorphism:

For a simple application of polymorphism, see Listing 1-1:

<span class="hljs-function"&gt;<span class="hljs-keyword"&gt;public <span class="hljs-keyword"&gt;static <span class="hljs-keyword"&gt;void <span class="hljs-title"&gt;main<span class="hljs-params"&gt;(String[] args) {
    <span class="hljs-comment"&gt;// <a href="https://www.jb51.cc/tag/fulei/" target="_blank" class="keywords">父类</a>引用指向子类对象
    Wanger[] wangers = { <span class="hljs-keyword"&gt;new Wanger(),<span class="hljs-keyword"&gt;new Wangxiaoer() };

    <span class="hljs-keyword"&gt;for (Wanger wanger : wangers) {
        <span class="hljs-comment"&gt;// 对象是王二的时候<a href="https://www.jb51.cc/tag/shuchu/" target="_blank" class="keywords">输出</a>:勿忘国耻
        <span class="hljs-comment"&gt;// 对象是王小二的时候<a href="https://www.jb51.cc/tag/shuchu/" target="_blank" class="keywords">输出</a>:记住仇恨,表明我们要奋发图强的心智
        wanger.write();
    }
}

< span class = "hljs class" > < span class = "hljs keyword" > class < span class = "hljs title" > Wanger {< span class = "hljs function" > < span class = "hljs keyword" > public < span class = "hljs keyword" > void < span class = "hljs title" > write < span class = "hljs params" > () {system.out.println (< span class = "hljs string > don't forget national humiliation");}}< H3 class = "heading" > 02 polymorphism and late binding

Now, let's think about a problem: program listing 1-1 is executing Wanger When writing (), since the compiler has only one Wanger reference, how does it know whether to call the write () method of the parent Wanger or the write () method of the child wangxiaoer?

The answer is that late binding is performed according to the type of the object at runtime. The compiler does not know the type of the object at the compilation stage, but Java's method calling mechanism can find the correct method body and execute the correct results.

Polymorphic mechanism provides an important benefit, and the program has good scalability. See procedure listing 2-1:

<span class="hljs-function"&gt;<span class="hljs-keyword"&gt;public <span class="hljs-keyword"&gt;void <span class="hljs-title"&gt;eat<span class="hljs-params"&gt;() {
    Sy<a href="https://www.jb51.cc/tag/stem/" target="_blank" class="keywords">stem</a>.out.println(<span class="hljs-string"&gt;"我不喜欢读书,我就喜欢吃");
}

<span class="hljs-function"&gt;<span class="hljs-keyword"&gt;public <span class="hljs-keyword"&gt;static <span class="hljs-keyword"&gt;void <span class="hljs-title"&gt;main<span class="hljs-params"&gt;(String[] args) {
    <span class="hljs-comment"&gt;// <a href="https://www.jb51.cc/tag/fulei/" target="_blank" class="keywords">父类</a>引用指向子类对象
    Wanger[] wangers = { <span class="hljs-keyword"&gt;new Wanger(),<span class="hljs-keyword"&gt;new Wangxiaoer() };

    <span class="hljs-keyword"&gt;for (Wanger wanger : wangers) {
        <span class="hljs-comment"&gt;// 对象是王二的时候<a href="https://www.jb51.cc/tag/shuchu/" target="_blank" class="keywords">输出</a>:勿忘国耻
        <span class="hljs-comment"&gt;// 对象是王小二的时候<a href="https://www.jb51.cc/tag/shuchu/" target="_blank" class="keywords">输出</a>:记住仇恨,表明我们要奋发图强的心智
        wanger.write();
    }
}

}

In listing 2-1, we added the read () method to the Wanger class and the eat () method to the wangxiaoer class, but this will not affect the call of the write () method at all. The write () method ignores the changes in the surrounding code and still works normally. This reminds me of the formula of the Nine Yang Sutra in Jin Yong's story of leaning on the sky and slaughtering the Dragon: "he is strong by him, the breeze blows the hills; he is horizontal by him, and the bright moon shines on the river."

This excellent feature of polymorphism allows us not to be too nervous when modifying code, because polymorphism is an important feature that allows programmers to "separate changed from unchanged".

Calling polymorphic methods in a constructor can produce a curious result. Let's look at the program list 3-1: parent class < / a > < a href =" " https://www.jb51.cc/tag/fangfa/ " target="_ Blank "class =" Keywords "> method

Downward transformation refers to the strong conversion of parent class references to child class types; This is not safe, because sometimes, the parent class reference points to the parent class object, and the downward transformation will throw ClassCastException, indicating that the type conversion fails; However, if the parent class reference points to a child class object, the downward transformation is successful. Look at program listing 4-1: < span class = "hljs function" & gt< span class="hljs-keyword"> public

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>