1.9(番外) Java复习之多态性练习

本文介绍了一个银行账户管理系统的设计与实现,重点展示了如何利用多态性特性支持多种类型的账户,包括储蓄账户和支票账户,并演示了账户间的交互操作。

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

文章目录


#多态性

这里写图片描述
注意format方法,将货币单位动态本地化(中国为人民币,美国为dollar)
##练习1
Account类

package banking5;


public class Account {
	protected double balance;//属性为protected,便于子类调用
	
	public Account(double init_balance){
		balance = init_balance;
	}
	
	public double getBalance(){
		return balance;
	}
	
	public boolean deposit(double amt){
		 balance += amt;
		 return true;
	}
	
	public boolean withdraw(double amt){
		if(balance >= amt){
			balance -= amt;
			return true;
		}else{
			  System.out.println("不足");
			  return false;
		}
	}
}

Bank类

package banking5;

public class Bank {
 private Customer[] customers;
 private int numberOfCustomer;//客户数量
 
 public Bank(){
	customers = new Customer[5]; 
 }
 
 public void addCustomer(String f,String l){
	 Customer cust = new Customer(f,l);
	 customers[numberOfCustomer] = cust;
     numberOfCustomer++;
 }

public int getNumOfCustomers() {
	return numberOfCustomer;
}

public Customer getCustomer(int index){
	return customers[index];
}
}

Class : CheckAccount

package banking5;

public class CheckAccount extends Account {
  private double overdraftProtection;
  public CheckAccount(double balance){
	  super(balance);
	  
  }
  public CheckAccount(double balance,double protect){
	  super(balance);
	  this.overdraftProtection = protect;
  }
  
  
  public double getOverdraftProtection() {
	return overdraftProtection;
}
public void setOverdraftProtection(double overdraftProtection) {
	this.overdraftProtection = overdraftProtection;
}
public boolean withdraw(double amt){
		if(balance >= amt){
			balance -= amt;
			//return true;
		}else if(overdraftProtection>= amt - balance){
			overdraftProtection -= (amt - balance);
			balance = 0;
			//return true;
		}else{
			return false;
		}
		return true; //合二为一,return true
	}
}

class : SavingAccount

package banking5;

public class SavingAccount extends Account { //储蓄账户
	private double interestRate;
	
	public SavingAccount(double balance,double interest_rate) {
		super(balance);
		this.interestRate = interest_rate;
		
	}

	public double getInterestRate() {
		return interestRate;
	}

	public void setInterestRate(double interestRate) {
		this.interestRate = interestRate;
	}
	
	
	
	

}

class : Customer

package banking5;

public class Customer {
	private String firstName;
	private String lastName;
	private Account account;
	
	public Customer(String f,String l){
		firstName = f;
		lastName = l;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public Account getAccount() {
		return account;
	}

	public void setAccount(Account acct) {//多态性,可将子类对象赋值
		this.account = acct;
	}	

}

class : TestBanking

package TestBanking;
/*
 * This class creates the program to test the banking classes.
 * It creates a new Bank, sets the Customer (with an initial balance),
 * and performs a series of transactions with the Account object.
 */

import banking5.*;

public class TestBanking5 {

  public static void main(String[] args) {
    Bank     bank = new Bank();
    Customer customer;
    Account account;

    //
    // Create bank customers and their accounts
    //

    System.out.println("Creating the customer Jane Smith.");
    bank.addCustomer("Jane", "Simms");
    
    account= new SavingAccount(500, 0.03);
    customer = bank.getCustomer(0);
    customer.setAccount(account);//四部曲,创建客户,账户,获取客户,绑定客户
    
    //code
    System.out.println("Creating her Savings Account with a 500.00 balance and 3% interest.");
    //code
    bank.addCustomer("Owen", "Bryant");
    System.out.println("Creating the customer Owen Bryant.");
    //code
    customer = bank.getCustomer(1);//通过该方法来调用customer
    account = new CheckAccount(500);
    customer.setAccount(account);
    System.out.println("Creating his Checking Account with a 500.00 balance and no overdraft protection.");
    //code
    
    System.out.println("Creating the customer Tim Soley.");
    bank.addCustomer("Tim", "Soley");
    customer = bank.getCustomer(2);
    account = new CheckAccount(500.00,500.00);
    customer.setAccount(account);
    System.out.println("Creating his Checking Account with a 500.00 balance and 500.00 in overdraft protection.");
    //code
    
    System.out.println("Creating the customer Maria Soley.");
   bank.addCustomer("Maria", "Soley");
    customer = bank.getCustomer(3);
    //account = bank.getCustomer(2).getAccount();
    //customer.setAccount(account);以上注释为省略部分
    System.out.println("Maria shares her Checking Account with her husband Tim.");//共享账户,不需重新创建账户
    customer.setAccount(bank.getCustomer(2).getAccount());

    System.out.println();

    //
    // Demonstrate behavior of various account types
    //

    // Test a standard Savings Account
    System.out.println("Retrieving the customer Jane Smith with her savings account.");
    customer = bank.getCustomer(0);
    account = customer.getAccount();
    // Perform some account transactions
    System.out.println("Withdraw 150.00: " + account.withdraw(150.00));
    System.out.println("Deposit 22.50: " + account.deposit(22.50));
    System.out.println("Withdraw 47.62: " + account.withdraw(47.62));
    System.out.println("Withdraw 400.00: " + account.withdraw(400.00));
    // Print out the final account balance
    System.out.println("Customer [" + customer.getLastName()
		       + ", " + customer.getFirstName()
		       + "] has a balance of " + account.getBalance());

    System.out.println();

    // Test a Checking Account w/o overdraft protection
    System.out.println("Retrieving the customer Owen Bryant with his checking account with no overdraft protection.");
    customer = bank.getCustomer(1);
    account = customer.getAccount();
    // Perform some account transactions
    System.out.println("Withdraw 150.00: " + account.withdraw(150.00));
    System.out.println("Deposit 22.50: " + account.deposit(22.50));
    System.out.println("Withdraw 47.62: " + account.withdraw(47.62));
    System.out.println("Withdraw 400.00: " + account.withdraw(400.00));
    // Print out the final account balance
    System.out.println("Customer [" + customer.getLastName()
		       + ", " + customer.getFirstName()
		       + "] has a balance of " + account.getBalance());

    System.out.println();

    // Test a Checking Account with overdraft protection
    System.out.println("Retrieving the customer Tim Soley with his checking account that has overdraft protection.");
    customer = bank.getCustomer(2);
    account = customer.getAccount();
    // Perform some account transactions
    System.out.println("Withdraw 150.00: " + account.withdraw(150.00));
    System.out.println("Deposit 22.50: " + account.deposit(22.50));
    System.out.println("Withdraw 47.62: " + account.withdraw(47.62));
    System.out.println("Withdraw 400.00: " + account.withdraw(400.00));
    // Print out the final account balance
    System.out.println("Customer [" + customer.getLastName()
		       + ", " + customer.getFirstName()
		       + "] has a balance of " + account.getBalance());

    System.out.println();

    // Test a Checking Account with overdraft protection
    System.out.println("Retrieving the customer Maria Soley with her joint checking account with husband Tim.");
    customer = bank.getCustomer(3);
    account = customer.getAccount();
    // Perform some account transactions
    System.out.println("Deposit 150.00: " + account.deposit(150.00));
    System.out.println("Withdraw 750.00: " + account.withdraw(750.00));
    // Print out the final account balance
    System.out.println("Customer [" + customer.getLastName()
		       + ", " + customer.getFirstName()
		       + "] has a balance of " + account.getBalance());

  }
}

##练习2

修改Customer类

package banking5_1;

public class Customer {
	private String firstName;
	private String lastName;
	private Account[] accounts;
	private int numOfAccounts;
	
	public Customer(String f,String l){
		firstName = f;
		lastName = l;
		accounts = new Account[5];
	}
	public void addAccount(Account account){
		 accounts[numOfAccounts] = account;//次序别反了
		 numOfAccounts++;
		
	}
	public int getNumOfAccounts(){//public易忘
		return numOfAccounts;
	}
	public Account getAccount(int index){
		return accounts[index];
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	

}

测试类

package TestBanking;
/*
 * This class creates the program to test the banking classes.
 * It creates a set of customers, with a few accounts each,
 * and generates a report of current account balances.
 */

import banking5_1.*;
import java.text.NumberFormat;

public class TestBanking5_1 {

  public static void main(String[] args) {
    NumberFormat currency_format = NumberFormat.getCurrencyInstance();
    Bank     bank = new Bank();
    Customer customer;

    // Create several customers and their accounts
    bank.addCustomer("Jane", "Simms");
    customer = bank.getCustomer(0);
    customer.addAccount(new SavingAccount(500.00, 0.05));
    customer.addAccount(new CheckAccount(200.00, 400.00));

    bank.addCustomer("Owen", "Bryant");
    customer = bank.getCustomer(1);
    customer.addAccount(new CheckAccount(200.00));

    bank.addCustomer("Tim", "Soley");
    customer = bank.getCustomer(2);
    customer.addAccount(new SavingAccount(1500.00, 0.05));
    customer.addAccount(new CheckAccount(200.00));

    bank.addCustomer("Maria", "Soley");
    customer = bank.getCustomer(3);
    // Maria and Tim have a shared checking account
    customer.addAccount(bank.getCustomer(2).getAccount(1));
    customer.addAccount(new SavingAccount(150.00, 0.05));

    // Generate a report
    System.out.println("\t\t\tCUSTOMERS REPORT");
    System.out.println("\t\t\t================");

    for ( int cust_idx = 0; cust_idx < bank.getNumOfCustomers(); cust_idx++ ) {
      customer = bank.getCustomer(cust_idx);

      System.out.println();
      System.out.println("Customer: "
			 + customer.getLastName() + ", "
			 + customer.getFirstName());

      for ( int acct_idx = 0; acct_idx < customer.getNumOfAccounts(); acct_idx++ ) {
	Account account = customer.getAccount(acct_idx);
	String  account_type = "";

	// Determine the account type
	/*** Step 1:
	**** Use the instanceof operator to test what type of account
	**** we have and set account_type to an appropriate value, such
	**** as "Savings Account" or "Checking Account".
	***/
     if(account instanceof SavingAccount){
    	 account_type = "SavingAccount";
     }
     if(account instanceof CheckAccount){
    	 account_type = "CheckAccount";
     }
	// Print the current balance of the account
	/*** Step 2:
	**** Print out the type of account and the balance.
	**** Feel free to use the currency_format formatter
	**** to generate a "currency string" for the balance.
	***/
     System.out.println(account_type+ ": current balance is "+currency_format.format(account.getBalance()));
     //关注最后代码段,货币符号的动态本地化
     //打印代码的书写值得学习(两层循环,外层控制不同客户,内层同一客户不同账户)
      }
    }
  }
}

运行截图

			CUSTOMERS REPORT
			================

Customer: Simms, Jane
SavingAccount: current balance is ¥500.00
CheckAccount: current balance is ¥200.00

Customer: Bryant, Owen
CheckAccount: current balance is ¥200.00

Customer: Soley, Tim
SavingAccount: current balance is ¥1,500.00
CheckAccount: current balance is ¥200.00

Customer: Soley, Maria
CheckAccount: current balance is ¥200.00
SavingAccount: current balance is ¥150.00

上述练习学习类间的联系以及多态的使用
多态指的是子类账户实体对象赋值给父类对象引用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值