本文適用於學習完類繼承找小demo練習的選手。
如有錯誤還請指正。
1.寫在前面
對繼承類操作的複習,並對項目進行總結。
2.項目結構編寫
項目目標
由群主發紅包,群員搶紅包。需要能設定發紅包的個數和金額,並且能通過執行方法知道任意成員當前所擁有的金額。
this、super關鍵字的總結
在繼承開始之前,得先了解this和super關鍵字。
super關鍵字有三種用法
1.在子類成員方法中,訪問父類成員變量
2.在子類成員方法中,訪問父類成員方法
3.在子類構造方法中,訪問父類構造方法
注:在構造方法中默認有一個super()方法(不傳參!)
注:3中super(…)必須為第一個語句
this關鍵字有三種用法
1.在本類成員方法中,訪問本類成員變量
2.在本類成員方法中,訪問本類成員方法(this可省略)
3.在本類構造方法中,訪問本類構造方法
注:3中this(…)必須為第一個語句
所以this和super不能同時使用,即寫下this時,默認的super方法將不再贈送
但有另外一種情況
class A extends B {
public A(int i){
this.A();
}
public A(){
// 此處的super();依舊贈送
}
}
類的結構
父類
類名:User
public class User {
private String name;
private double money;
public User(String name, double money){
this.name = name;
this.money = money;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setMoney(double money){
this.money = money;
}
public double getMoney(){
return money;
}
public void show(){
System.out.println(this.name + "還有" + money + "元");
}
}
子類1
類名:Manager
import java.util.ArrayList;
import java.util.Random;
import static java.lang.Math.floor;
public class Manager extends User {
public Manager(String name, double money){
super(name, money);
}
public ArrayList<double> send(double totalMoney, int count){/<double>
ArrayList<double> list = new ArrayList<>();/<double>
if(totalMoney > super.getMoney()){
System.out.println("餘額不足");
return list;
}
for(int i = 0; i < count - 1; i++){
Random r = new Random();
double pkg = floor(r.nextDouble()*0.5*totalMoney*100)/100;
list.add(pkg);
totalMoney -= pkg;
}
list.add(totalMoney);
return list;
}
}
子類2
類名:Member
import java.util.ArrayList;
import java.util.Random;
public class Member extends User {
public Member(String name, double money){
super(name, money);
}
public void receive(ArrayList<double> list){/<double>
int index = new Random().nextInt(list.size());
double catchMoney = list.remove(index);
System.out.println(super.getName() + "搶到了" + catchMoney + "元");
super.setMoney(catchMoney + super.getMoney());
}
}
3.主方法的編寫
import java.util.ArrayList;
public class Red_Package{
public static void main(String[] args){
Manager manager = new Manager("manager", 100);
Member one = new Member("one", 0);
Member two = new Member("two", 0);
Member three = new Member("three", 0);
manager.show();
one.show();
two.show();
three.show();
ArrayList<double> list = manager.send(50, 3);/<double>
one.receive(list);
two.receive(list);
three.receive(list);
manager.show();
one.show();
two.show();
three.show();
}
}
4.項目總結
1.在運行中可能會出現結果為例如搶到紅包的錢數為1.00000000003的情況,初步猜測系double類型精度問題導致,暫未考證。
2.當群主發紅包錢數大於當前持有錢數,在輸出"餘額不足"後會終止程序運行,暫未想出解決方法。
閱讀更多 架構師公社 的文章