inherit.java

来自「Java 入门书的源码」· Java 代码 · 共 56 行

JAVA
56
字号
//Copyright (c) 1998, Arthur Gittleman
//This example is provided WITHOUT ANY WARRANTY either expressed or implied.

/* Defines SavingsAccount and CheckingAccount
 * of BankAccount.  Inherit class uses these 
 * classes to illustrate inheritance.
 */

import iopack.Io;
class SavingsAccount extends BankAccount  {
  private double interestRate;
  public SavingsAccount(double amount, double rate) {
     super(amount);
     interestRate = rate;
  }     
  public void postInterest()  {
    double balance = getBalance();
    double interest = interestRate/100*balance;
    setBalance(balance + interest);
  }
}   
class CheckingAccount extends BankAccount {  
  private double minBalance;
  private double charge;
  public CheckingAccount(double minAmount, double charge) {
    super();
    minBalance = minAmount;
    this.charge = charge;
  }
  public void processCheck(double amount)  {
    if (getBalance() >= minBalance)
      super.withdraw(amount);
    else 
      super.withdraw(amount + charge);      
  }
  public void withdraw(double amount) {
    processCheck(amount);
  }
} 
public class Inherit {
  public static void main(String [] args) {
    SavingsAccount s =  new SavingsAccount(500.00, 4.5);
    CheckingAccount c = new CheckingAccount(2500.00, .50);
    s.deposit(135.22);
    s.postInterest();
    s.withdraw(50);
    System.out.print("The balance of SavingsAccount s is ");  
    Io.println$(s.getBalance()); 
    c.deposit(1000.00);
    c.processCheck(200.00);
    c.withdraw(100.00);
    System.out.print("The balance of CheckingAccount c is ");  
    Io.println$(c.getBalance());
    Io.readString("Press any key to exit");   // Added for IDE use
  }
}  

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?