类的继承(发红包案例)

package redpacket;

/**
 * 定义好姓名、余额属性
 */
public class User {
    private String name;
    private int money;

    public User() {
    }

    public User(String name, int money) {
        this.name = name;
        this.money = money;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getMoney() {
        return money;
    }

    public void setMoney(int money) {
        this.money = money;
    }

    /**
     * 显示成员基本信息
     */
    public void show() {
        System.out.println("name: " + name + " money: " + money);
    }
}

package redpacket;

import java.util.ArrayList;

/**
 * 群主 负责发红包
 */
public class Manager extends User {
    public Manager() {
    }

    public Manager(String name, int money) {
        super(name, money);
    }

    /**
     * 发红包的具体实现
     *
     * @param totalMoney 红包总额
     * @param count      份数
     * @return 多个份数红包
     */
    public ArrayList send(int totalMoney, int count) {
        //实例化一个红包容器
        ArrayList list = new ArrayList<>();
        //判断群主是否有能力发红包
        if (totalMoney > super.getMoney()) {
            System.out.println("你的余额不足");
            return list;
        }

        //扣除金额
        super.setMoney(super.getMoney() - totalMoney);

        //将红包拆成count份,余额给最后一份
        int avg = totalMoney / count;
        int mod = totalMoney % count;

        //装红包
        for (int i = 0; i < count - 1; i++) {
            list.add(avg);
        }


        list.add(avg + mod);

        return list;
    }
}

package redpacket;

import java.util.ArrayList;
import java.util.Random;

public class Number extends User {
    public Number() {
    }

    public Number(String name, int money) {
        super(name, money);
    }

    /**
     * 收红包
     * @param list 总红包
     */
    public void recive(ArrayList list) {
        int i = new Random().nextInt(list.size());

        Integer remove = list.remove(i);

        //获取红包 并加入自己的余额
        super.setMoney(super.getMoney() + remove);
    }
}

package redpacket;

import java.util.ArrayList;

public class DemoMain {
    public static void main(String[] args) {
        Manager manager = new Manager("manager", 200);
        Number one = new Number("one", 0);
        Number two = new Number("two", 0);
        Number three = new Number("three", 0);

        manager.show();
        one.show();
        two.show();
        three.show();

        ArrayList send = manager.send(100, 3);
        one.recive(send);
        two.recive(send);
        three.recive(send);

        manager.show();
        one.show();
        two.show();
        three.show();
    }
}

你可能感兴趣的:(类的继承(发红包案例))