Core Java Programming (CE0421)
Practical : Write a Java program to create a class known as "BankAccount" with methods called
deposit() and withdraw(). Create a subclass called SavingsAccount that overrides the withdraw()
method to prevent withdrawals if the account balance falls below one hundred.
Code:
public class Main {
public static void main(String[] args) {
BankAccount acc = new BankAccount();
acc.deposit(500);
acc.withdraw(200);
System.out.println("Current Balance: " + acc.getBalance());
SavingsAccount savingsAcc = new SavingsAccount();
savingsAccount.deposit(300);
savingsAccount.withdraw(150);
System.out.println("Savings Account Balance: " + savingsAccount.getBalance());
savingsAccount.withdraw(100);
System.out.println("Savings Account Balance after withdrawal: " +
savingsAccount.getBalance());
savingsAccount.withdraw(50);
System.out.println("Savings Account Balance after attempted withdrawal: " +
savingsAccount.getBalance());
}
}
class BankAccount {
private double balance;
public BankAccount() {
this.balance = 0.0;
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposited: " + amount);
} else {
System.out.println("Deposit amount must be positive.");
}
}
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("Withdrew: " + amount);
} else
IU2341230377 B.Tech CSE-D1
Core Java Programming (CE0421)
{
System.out.println("Insufficient balance or invalid amount.");
}
}
public double getBalance() {
return balance;
}
}
class SavingsAccount extends BankAccount {
private static final double MIN_BALANCE = 100.0;
@Override
public void withdraw(double amount) {
if (amount > 0 && (getBalance() - amount) >= MIN_BALANCE) {
super.withdraw(amount);
} else {
System.out.println("Withdrawal denied. Minimum balance of " + MIN_BALANCE + "
must be maintained.");
}
}
}
Output:
Signature Date
IU2341230377 B.Tech CSE-D1