Java Polymorphism: BankAccount base class with Savings, Checking Account subclasses
Write a Java program to create a base class BankAccount with methods deposit() and withdraw(). Create two subclasses SavingsAccount and CheckingAccount. Override the withdraw() method in each subclass to impose different withdrawal limits and fees.
Sample Solution:
Java Code:
Output:
Savings Account Balance: 1700.0 Checking Account Balance: 750.0
Explanation:
In the above exercise -
- The "BankAccount" class is the base class, and SavingsAccount and CheckingAccount are its subclasses. Each subclass overrides the withdraw() method to impose different withdrawal limits and fees based on their specific rules.
- In the "Main" class, we have a static method withdrawFromAccount(BankAccount account, double amount) that takes an object of the base class BankAccount as a parameter. Inside this method, we call the withdraw() method on the account object. Since the withdrawFromAccount method takes a BankAccount type parameter, it can accept SavingsAccount and CheckingAccount objects, thanks to polymorphism.
Flowchart:




For more Practice: Solve these Related Problems:
- Write a Java program where the "BankAccount" class supports overdraft protection for CheckingAccount.
- Write a Java program where the "BankAccount" class includes a method to transfer money between accounts.
- Write a Java program where the "BankAccount" class tracks transaction history.
- Write a Java program where the "BankAccount" class applies a service fee for withdrawals.
Go to:
Java Code Editor:
Contribute your code and comments through Disqus.
PREV : Shape base class with Circle, Square, and Triangle subclasses.
NEXT : Animal base class with Lion, Tiger, and Panther subclasses.
What is the difficulty level of this exercise?