You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现抽象类与继承类的交互?基于@Override的账户类实现咨询

Hey there! Let's work through this account implementation step by step to make sure all your business rules are covered properly. First, let's lay out the requirements clearly so we don't miss anything:

需求梳理

  • Create an abstract Account class with three core methods: pay(int amount), transfer(Account account, int amount), and addMoney(int amount)
  • Every account must maintain a balance property
  • SavingsAccount: Only supports transfers and deposits, cannot process payments; balance can never be negative
  • CreditAccount: Balance can never be positive; payments make the balance negative; deposits can only restore the balance to 0 (can't make it positive)
  • CheckingAccount: Must implement all three methods; balance can never be negative
  • Need to create three Account-typed variables corresponding to each account type

完整实现代码

First, we'll fix the abstract Account class to use abstract methods (so subclasses are forced to implement them with @Override), and clean up unnecessary properties:

public abstract class Account {
    protected int balance;

    // Constructor: Initialize balance, subclasses will handle rule validation
    public Account(int initialBalance) {
        this.balance = initialBalance;
    }

    // Abstract methods that subclasses must implement
    public abstract void pay(int amount);
    public abstract void transfer(Account targetAccount, int amount);
    public abstract void addMoney(int amount);

    // Helper method to access balance from outside the class
    public int getBalance() {
        return balance;
    }
}

CheckingAccount Implementation

public class CheckingAccount extends Account {
    public CheckingAccount(int initialBalance) {
        super(initialBalance);
        // Ensure initial balance isn't negative
        if (balance < 0) {
            throw new IllegalArgumentException("Checking account balance can't be negative");
        }
    }

    @Override
    public void pay(int amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException("Payment amount must be positive");
        }
        // Only allow payment if balance is sufficient
        if (balance >= amount) {
            balance -= amount;
        } else {
            throw new IllegalStateException("Insufficient balance for payment");
        }
    }

    @Override
    public void transfer(Account targetAccount, int amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException("Transfer amount must be positive");
        }
        // Reuse pay() logic for deduction, then add to target account
        this.pay(amount);
        targetAccount.addMoney(amount);
    }

    @Override
    public void addMoney(int amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException("Deposit amount must be positive");
        }
        balance += amount;
    }
}

CreditAccount Implementation

public class CreditAccount extends Account {
    public CreditAccount(int initialBalance) {
        super(initialBalance);
        // Ensure initial balance isn't positive
        if (balance > 0) {
            throw new IllegalArgumentException("Credit account balance can't be positive");
        }
    }

    @Override
    public void pay(int amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException("Payment amount must be positive");
        }
        // Payments increase the negative balance (since we can't go positive)
        balance -= amount;
    }

    @Override
    public void transfer(Account targetAccount, int amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException("Transfer amount must be positive");
        }
        // Treat transfer as a payment to the target account
        this.pay(amount);
        targetAccount.addMoney(amount);
    }

    @Override
    public void addMoney(int amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException("Deposit amount must be positive");
        }
        // Deposit can only bring balance up to 0, not above
        balance = Math.min(balance + amount, 0);
    }
}

SavingsAccount Implementation

public class SavingsAccount extends Account {
    public SavingsAccount(int initialBalance) {
        super(initialBalance);
        // Ensure initial balance isn't negative
        if (balance < 0) {
            throw new IllegalArgumentException("Savings account balance can't be negative");
        }
    }

    @Override
    public void pay(int amount) {
        // Savings accounts don't support payments, throw clear exception
        throw new UnsupportedOperationException("Savings accounts do not support payment operations");
    }

    @Override
    public void transfer(Account targetAccount, int amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException("Transfer amount must be positive");
        }
        // Only allow transfer if balance is sufficient
        if (balance >= amount) {
            balance -= amount;
            targetAccount.addMoney(amount);
        } else {
            throw new IllegalStateException("Insufficient balance for transfer");
        }
    }

    @Override
    public void addMoney(int amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException("Deposit amount must be positive");
        }
        balance += amount;
    }
}

Test Code (to demonstrate usage)

public class AccountDemo {
    public static void main(String[] args) {
        // Create Account-typed variables for each account type
        Account checking = new CheckingAccount(1000);
        Account credit = new CreditAccount(0);
        Account savings = new SavingsAccount(5000);

        // Example operations
        checking.pay(200);
        System.out.println("Checking Account Balance: " + checking.getBalance()); // Output: 800

        credit.pay(500);
        System.out.println("Credit Account Balance After Payment: " + credit.getBalance()); // Output: -500
        credit.addMoney(300);
        System.out.println("Credit Account Balance After Deposit: " + credit.getBalance()); // Output: -200

        savings.transfer(checking, 1000);
        System.out.println("Savings Account Balance After Transfer: " + savings.getBalance()); // Output: 4000
        System.out.println("Checking Account Balance After Transfer: " + checking.getBalance()); // Output: 1800
    }
}

Key Implementation Details

  • Abstract Account Class: Converted methods to abstract to enforce subclass implementation, added a getBalance() helper for external access, and removed the redundant amount instance variable (operation amounts are passed as method parameters instead)
  • CheckingAccount: Reuses pay() logic for transfers to avoid code duplication, and validates all operations to ensure balance stays non-negative
  • CreditAccount: Uses Math.min() in addMoney() to cap balance at 0, ensuring it never goes positive
  • SavingsAccount: Explicitly throws UnsupportedOperationException for pay() to clearly communicate that payments are not allowed

内容的提问来源于stack exchange,提问作者Андрей Лобков

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 15:02:59