Home  >  Article  >  Java  >  What is java polymorphism? The use of java polymorphism

What is java polymorphism? The use of java polymorphism

青灯夜游
青灯夜游forward
2018-10-20 17:56:053175browse

What this article brings to you is what is java polymorphism? The use of java polymorphism, through some functions in the game, will help you master the use of polymorphism. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Why use polymorphism

In a battle game (any similarities are purely coincidental), there are two different mage heroes: Xiao Qiao and Daji.
Both mage heroes have attack methods. Xiao Qiao's attack damage is 10 and consumes 20 mana. Daji's attack damage is 15 and consumes 30 mana. Players can operate two heroes to attack. Let’s take a look at the implemented code.

Parent class-Hero: whyusepolymorphic.Hero.java

package whyusepolymorphic;

public class Hero {
    private int magicPoint;//魔法值
    private int hurt;//伤害
    private String name;//姓名
    
    public Hero(int magicPoint, int hurt, String name) {
        super();
        this.magicPoint = magicPoint;
        this.hurt = hurt;
        this.name = name;
    }

    public int getMagicPoint() {
        return magicPoint;
    }

    public void setMagicPoint(int magicPoint) {
        this.magicPoint = magicPoint;
    }
    
    //省略属性的 getter 和 setter 方法
}

Subclass-Little Joe: whyusepolymorphic.LittleJoe.java

package whyusepolymorphic;

public class LittleJoe extends Hero {

    public LittleJoe(int magicPoint, int hurt, String name) {
        super(magicPoint, hurt, name);
    }

    //攻击的方法
    public void attack() {
        System.out.println(this.getName()+" 发动攻击,伤害为:"+this.getHurt()
        +"。消耗 20的魔法值");
        this.setMagicPoint(getMagicPoint()-20);//魔法值-20
    }

}

Subclass-Daji:whyusepolymorphic.Daji.java

package whyusepolymorphic;

public class Daji extends Hero{

    public Daji(int magicPoint, int hurt, String name) {
        super(magicPoint, hurt, name);
    }
    
    public void attack() {
        System.out.println(this.getName()+" 发动攻击,伤害为:"+this.getHurt()
        +"。消耗 30的魔法值");
        this.setMagicPoint(getMagicPoint()-30);//魔法值-30
    }
}

Player:whyusepolymorphic.Player.java

package whyusepolymorphic;

public class Player {
    public void play(LittleJoe littleJoe) {
        littleJoe.attack();
    }
    public void play(Daji daji) {
        daji.attack();
    }
}

The above code is complete After realizing the requested function, we know that there cannot be only these few heroes. What if new magic heroes are added later and the damage is different?

We can add new classes to implement attack methods, and modify the player class to add methods for operating heroes. This method can meet the needs of Hero expansion, but if more Heroes are added later, it will not be so convenient for us to maintain.

Studying the above code, we found that the parameters of the play method in the Player class are all subclasses of the Hero class. Can one play(Hero hero) method be used to operate all heroes? This optimized design can be achieved using polymorphism.

What is polymorphism

Concisely, polymorphism means multiple forms. Polymorphic forms of carbon in nature include graphite, diamond, etc. The action of cutting includes paper cutting, hair cutting, etc. The same operation produces different results due to different conditions.

Then polymorphism in the program refers to the same reference type, using different instances to perform different operations (the parent class reference specifies the subclass objectHero h=new Daji();).

How to implement polymorphism

Steps to implement polymorphism:

1. Write parent classes and subclasses# with inheritance relationships

##2.

The subclass overrides the parent class method

3. Use the

reference of the parent class to point to the object of the subclass

The parent class serves as Method parameters implement polymorphism

Use polymorphism to optimize the above code

Modify Hero.java to add attack methods

package whyusepolymorphic;

public class Hero {
    //省略属性和构造方法
    
    //攻击的方法
    public void attack() {
        System.out.println(this.getName()+" 发动攻击,伤害为:"+this.getHurt()
        +"。消耗 20的魔法值");
        this.setMagicPoint(getMagicPoint()-20);//魔法值-20
    }
    //省略 getter 和 setter 方法
}
No need to modify the two subclasses

Modify the player class Player.java and set the parameters of the play method to the parent class

package whyusepolymorphic;

public class Player {
    public void play(Hero hero) {
        hero.attack();
    }
}
Modify the test class

package whyusepolymorphic;

public class TestPlay {
    public static void main(String[] args) {
        Player p=new Player();
        Hero daji=new Daji(100,15,"妲己");
        p.play(daji);
        System.out.println(daji.getName()+" 剩余魔法:"+daji.getMagicPoint());
        Hero littleJoe=new LittleJoe(100,10,"小乔");
        p.play(littleJoe);
        System.out.println(littleJoe.getName()+" 剩余魔法:"+littleJoe.getMagicPoint());
    }
}
The parent class is used as the return value to implement polymorphism

Players purchase heroes to use Polymorphic implementation, the purchase method has a return value, returns the purchased hero, and the parent class implements this function as the return value.

Modify the player class Player.java and add a method to get the hero

package whyusepolymorphic;

public class Player {
    public void play(Hero hero) {
        hero.attack();
    }
    
    public Hero getHero(int id) {
        if(1==id) {
            return new Daji(100,15,"妲己");
        }else if(2==id){
            return new LittleJoe(100,10,"小乔");
        }else {
            System.out.println("没有这个英雄");
            return null;
        }
    }
}
Test class

package whyusepolymorphic;

import java.util.Scanner;

public class TestPlay {
    public static void main(String[] args) {
        Player p=new Player();
        System.out.println("欢迎来到英雄商店,请选择要购买的英雄:1.妲己2.小乔");
        Scanner input=new Scanner(System.in);
        int id=input.nextInt();
        Hero h=p.getHero(id);
        if(null!=h) {
            h.attack();
        }
    }
}
Conversion from parent class to subclass

If in the subclass There are some methods unique to subclasses, and parent class references cannot call methods unique to subclasses.

Add a method queenWorship to Daji.java

package whyusepolymorphic;

public class Daji extends Hero{
    //省略构造方法及之前其他方法
    public void queenWorship() {
        System.out.println("释放大招:女王崇拜");
    }
}
Add a method dazzlingStar to LittleJoe.java

package whyusepolymorphic;

public class LittleJoe extends Hero {
    //省略构造方法及之前其他方法
    public void dazzlingStar() {
        System.out.println("释放大招:星华缭乱");
    }
}
Add a bigMove method to Player.java

package whyusepolymorphic;

public class Player {
    //省略构造方法及之前其他方法
    public void bigMove(Hero hero) {
        hero.dazzlingStar();
    }
}
Found code

hero.dazzlingStar(); Error reporting

At this time, you need to convert the parent class to a subclass (forced type conversion)

Hero joe=new LittleJoe(100,10,"小乔");
Daji daji=(Daji) joe;
But directly Writing like this will also report an error. Using the instanceof operator can ensure that there will be no conversion errors.

Syntax:

对象 instanceof 类或接口

instanceof is usually used in conjunction with forced type conversion.
Modify Player.java The bigMove method

public void bigMove(Hero hero) {
        if (hero instanceof Daji) {
            ((Daji)hero).queenWorship();
        }else if(hero instanceof LittleJoe) {
            ((LittleJoe)hero).dazzlingStar();
        }
    }
Write test code in the main method

Player p=new Player();
p.bigMove(new LittleJoe(100,10,"小乔"));
p.bigMove(new Daji(100,15,"妲己"));
Summary: The above is the entire content of this article, I hope it will be helpful to everyone's learning. For more related tutorials, please visit

Java video tutorial, java development graphic tutorial, bootstrap video tutorial!

The above is the detailed content of What is java polymorphism? The use of java polymorphism. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete