java銀行賬戶類
❶ java定義一個類實現銀行賬戶的概念。
public class BankAccount {
String account ;
int account_num;
//構造函數
public BankAccount(String account,int account_num){
this.account=account;
this.account_num=account_num;
}
//存錢
public String addNum(int num){
account_num= account_num+num;
return "存錢成功";
}
//取錢
public String getNum(int num){
String result;
if(account_num>num){
account_num =account_num-num;
result="取錢成功";
}else{
result="賬戶余額不足,還剩"+account_num;
}
return result;
}
//顯示余額
public String displayNum(){
return "賬戶余額:"+account_num;
}
//顯示賬號
public String displayAccount(){
return "賬戶:"+account;
}
public static void main(String[] args){
BankAccount lucy = new BankAccount("lucy",100);
BankAccount jack = new BankAccount("jack",50);
//顯示他們各自的余額
System.out.println("===顯示他們各自的余額===");
System.out.println("lucy:"+lucy.displayNum());
System.out.println("jack:"+jack.displayNum());
//存錢取錢
System.out.println("===存錢取錢===");
System.out.println("lucy取50:"+lucy.getNum(50));
System.out.println("jack存200:"+jack.addNum(200));
//顯示賬戶 顯示余額
System.out.println("===存錢取錢===");
System.out.println(lucy.displayAccount()+""+lucy.displayNum());
System.out.println(jack.displayAccount()+""+jack.displayNum());
}
}
運行結果:
===顯示他們各自的余額===
lucy:賬戶余額:100
jack:賬戶余額:50
===存錢取錢===
lucy取50:取錢成功
jack存200:存錢成功
===存錢取錢===
賬戶:lucy賬戶余額:50
賬戶:jack賬戶余額:250