26. [usage] reference type

Outline

The actual development, reference type of use is very important, but also very popular. We can understand the basic type of use on further references to master type of use.

Basic types can be used as a member variable as a parameter method, as the method's return value, of course, a reference type is also possible.

Class as a member variable

Game character class

When defining a class Role (game character), as follows:

package test.demo09;
// 英雄
public class Role {
    int id; // 角色ID
    int blood; // 生命值
    String name; // 角色名称
}

Use inttype represents character id and value of life, the use of Stringtype represents the name. At this time, stringis itself a reference type, similar to that used constant because of the way, so it is often overlooked type of reference exists.

If we continue to enrich this class definition, to Roleincrease the weapons, equipment and other property wear, how we write it?

Weapons class

The definition of weapon class that will increase attack capability:

package test.demo09;
// 武器
public class Weapon {
    String name; // 武器名称
    int hurt; // 伤害值
    
	// 省略构造器和get/set
}

Armor Class

Defined wear armor class, will increase defense capability, that is, to enhance the value of life:

package test.demo09;
// 护甲
public class Armor {
    String name; // 护甲名称
    int protect; // 防御值

    // 省略构造器和get/set
}

Code

The role of class

package test.demo09;
// 英雄
public class Role {
    int id; // 角色ID
    int blood; // 生命值
    String name; // 角色名称

    // 添加武器属性
    Weapon weapon;
    // 添加护甲属性
    Armor armor;

    // 提供get/set方法
    public Weapon getWeapon() {
        return weapon;
    }

    public void setWeapon(Weapon weapon) {
        this.weapon = weapon;
    }

    public Armor getArmor() {
        return armor;
    }

    public void setArmor(Armor armor) {
        this.armor = armor;
    }

    // 攻击方法
    public void attack() {
        System.out.println("Role使用"+ weapon.getName() +",造成"
                           + weapon.getHurt() +"点伤害");
    }
    // 穿戴护甲
    public void wear() {
        // 增加防御,就是增加blood值
        this.blood += armor.getProtect();
        System.out.println("穿上"+ armor.getName() +",生命值增加"
                           + armor.getProtect());
    }
}

Test category

package test.demo09;

public class DemoMain {
    public static void main(String[] args) {
        // 创建Weapom对象
        Weapon w = new Weapon("AK-47",79);
        // 创建Armor对象
        Armor a = new Armor("防弹背心",35);
        // 创建Role对象
        Role r = new Role();

        // 设置武器属性
        r.setWeapon(w);
        // 设置护甲属性
        r.setArmor(a);

        // 攻击
        r.attack();
        // 穿戴护甲
        r.wear();
    }
}

result:

Role使用AK-47,造成79点伤害
穿上防弹背心,生命值增加35

Interface as a member variable

Interface is a method of packaging for the corresponding game, the skills can be seen as extensions of game characters. So, if you want to expand more powerful skills, we RoleRolecan increase the interface as a member variable, a different set of skills.

interface

  • We use an interface as a member variable to change at any skill, this design is more flexible, enhancing the scalability of the program.

  • When the interface as a member variable, it assignment operation, in fact, a subclass object is assigned to the interface.

Abstract methods define the interface and release skills

public interface Skill {

    void use(); // 释放技能的抽象方法
}

The role of class

public class Hero {

    private String name; // 英雄名称
    private Skill skill; // 英雄技能

    public void attack() {
        System.out.println("我叫" + name + ",开始释放技能");
//        new SkillImpl().use();
        skill.use(); // 调用接口中的抽象方法
        System.out.println("技能释放完毕");
    }

	// 省略构造器和get/set
}

Test category

// 使用接口Skill接口作为成员变量类型
public class DemoGame {

    public static void main(String[] args) {
        Hero hero = new Hero();
        hero.setName("夜玫瑰");

        // 1. 使用单独定义的实现类
        hero.setSkill(new SkillImpl());
        hero.attack();
        System.out.println("=================");

        // 2. 还可以使用匿名内部类
        Skill skill = new Skill() {
            @Override
            public void use() {
                System.out.println("pia~ pia~ pia~");
            }
        };
        hero.setSkill(skill);
        hero.attack();
        System.out.println("=================");

        // 3. 进一步简化,同时使用匿名内部类和匿名对象
        hero.setSkill(new Skill() {
            @Override
            public void use() {
                System.out.println("tu~ tu~ tu~");
            }
        });

        hero.attack();
    }
}

result:

我叫夜玫瑰,开始释放技能
Biu~ Biu~ Biu~
技能释放完毕
=================
我叫夜玫瑰,开始释放技能
pia~ pia~ pia~
技能释放完毕
=================
我叫夜玫瑰,开始释放技能
tu~ tu~ tu~
技能释放完毕

An interface as parameter and return value of the method

  • Interface as a parameter, passing it the subclass object.

  • Interface type as the return value, to return to its subclass object.

Code demonstrates:

import java.util.ArrayList;
import java.util.List;

/*
    接口作为方法的参数和返回值
		java.util.List正是ArrayList所实现的接口
 */
public class DemoInterface {

    public static void main(String[] args) {
        // 左边是接口名称,右边是实现类名称,这就是多态写法
        List<String> list = new ArrayList<>();

        List<String> result = addNames(list);

        for (int i = 0; i < result.size(); i++) {
            System.out.println(result.get(i));
        }
    }
    // List<String> list:进来的时候是空集合
    public static List<String> addNames(List<String> list) { 
        list.add("迪丽热巴");
        list.add("古力娜扎");
        list.add("马尔扎哈");
        return list;
    }
}

result:

迪丽热巴
古力娜扎
马尔扎哈

END

Published 27 original articles · won praise 0 · Views 161

Guess you like

Origin blog.csdn.net/qq_39720594/article/details/104772968