4-9面向对象编程(上)----综合练习1--Account与Customer

该博客展示了如何使用Java创建一个Account类,用于管理银行账户的存款、取款和查看余额等功能。同时,还创建了一个Customer类来关联客户和账户。在Test类中,进行了账户操作的实例演示,包括成功存款、成功取款以及因余额不足导致的取款失败情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
Account类:

public class Account {
 private int id;// 账号
 private double balance;// 余额
 private double annualInterestRate;// 年利率

public Account(int id, double balance, double annualInterestRate) {
  this.id = id;
  this.balance = balance;
  this.annualInterestRate = annualInterestRate;
 }

public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public double getBalance() {
  return balance;
 }
 public void setBalance(double balance) {
  this.balance = balance;
 }
 public double getAnnualInterestRate() {
  return annualInterestRate;
 }
 public void setAnnualInterestRate(double annualInterestRate) {
  this.annualInterestRate = annualInterestRate;
 }

public void withdraw(double amount) {
  if (balance < amount) {
   System.out.println("余额不足,取款失败!");
   return;
  }
  balance -= amount;
  System.out.println("成功取出:" + amount);
 }// 取钱
 public void deposit(double amount) {
  if (amount > 0) {
   balance += amount;
   System.out.println("成功存入:" + amount);
  }
 }// 存钱
}

Customer类:

public class Customer {
 private String firstName;
 private String lastName;
 private Account account;

public Customer(String f,String l) {
  this.firstName = f;
  this.lastName = l;
 }

public Account getAccount() {
  return account;
 }
 public void setAccount(Account account) {
  this.account = account;
 }
 public String getFirstName() {
  return firstName;
 }
 public String getLastName() {
  return lastName;
 }
}

Test类:

public class Test {
 public static void main(String[] args) {
  Customer cust = new Customer("Jane", "Smith");
  Account acct = new Account(1000, 2000, 0.0123);
  cust.setAccount(acct);

cust.getAccount().deposit(100);
  cust.getAccount().withdraw(960);
  cust.getAccount().withdraw(2000);
  System.out.println("Customer [" + cust.getLastName() + "," + cust.getFirstName() + "] has a account: id is "
    + cust.getAccount().getId() + ", annualInterestRate is "
    + cust.getAccount().getAnnualInterestRate() * 100 + "%, balance is " + cust.getAccount().getBalance());
 }
}

输出:

成功存入:100.0
成功取出:960.0
余额不足,取款失败!
Customer [Smith,Jane] has a account: id is 1000, annualInterestRate is 1.23%, balance is 1140.0
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

YY鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值