Java继承类有没有大神帮帮我
定义储蓄罐(封装) a.属性:储蓄金额
b.定义方法:
1>存钱方法:参数为存钱的金额,判断存钱 的金额必须是正整数,且为10或5的倍数
2>取钱方法:有返回值,返回取钱金额,并 且每次取钱必须为2的倍数,否则取钱失败,取钱成功显示总金额
c.定义测试类
public class SavingsAccount { private int balance; public SavingsAccount(int balance) { this.balance = balance; } public void deposit(int amount) { if (amount > 0 && (amount % 10 == 0 || amount % 5 == 0)) { balance += amount; System.out.println("成功存入" + amount + "元,当前余额为" + balance + "元"); } else { System.out.println("存入金额必须为正整数且为10或5的倍数"); } } public int withdraw(int amount) { if (amount % 2 != 0) { System.out.println("取款金额必须为2的倍数"); return 0; } else if (amount > balance) { System.out.println("余额不足"); return 0; } else { balance -= amount; System.out.println("成功取出" + amount + "元,当前余额为" + balance + "元"); return amount; } } public int getBalance() { return balance; } }
public class SavingsAccountTest { public static void main(String[] args) { SavingsAccount account = new SavingsAccount(1000); account.deposit(50); account.deposit(15); account.deposit(-10); account.deposit(7); account.deposit(12); account.withdraw(5); account.withdraw(7); account.withdraw(100); account.withdraw(20); account.withdraw(30); System.out.println("当前余额为:" + account.getBalance()); } }