0% found this document useful (0 votes)
4 views

java 8 - 1

Uploaded by

karthan.official
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

java 8 - 1

Uploaded by

karthan.official
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

//First Program : MyPack/BankAccount.

java

package MyPack;

public class BankAccount {


private String accountHolder;
private double balance;

// Constructor
public BankAccount(String accountHolder, double initialBalance) {
this.accountHolder = accountHolder;
this.balance = initialBalance;
}

// Deposit method
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposited: $" + amount);
} else {
System.out.println("Invalid deposit amount.");
}
}

// Withdraw method
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("Withdrew: $" + amount);
} else {
System.out.println("Invalid withdrawal amount.");
}
}

// Get balance method


public double getBalance() {
return balance;
}

// Display account details


public void displayAccountInfo() {
System.out.println("Account Holder: " + accountHolder);
System.out.println("Balance: $" + balance);
}
}

//Second Program : MyPack/SavingsAccount.java

package MyPack;

public class SavingsAccount extends BankAccount {


private double interestRate;

// Constructor
public SavingsAccount(String accountHolder, double initialBalance, double
interestRate) {
super(accountHolder, initialBalance);
this.interestRate = interestRate;
}
// Apply interest
public void applyInterest() {
double interest = getBalance() * (interestRate / 100);
deposit(interest);
System.out.println("Interest applied: $" + interest);
}

// Override account info display to include interest rate


@Override
public void displayAccountInfo() {
super.displayAccountInfo();
System.out.println("Interest Rate: " + interestRate + "%");
}
}

//Main Program : MainClass.java

import MyPack.BankAccount;
import MyPack.SavingsAccount;

public class MainClass {


public static void main(String[] args) {
// Create a BankAccount object
BankAccount account1 = new BankAccount("Alice", 1000);
account1.displayAccountInfo();
account1.deposit(500);
account1.withdraw(300);
account1.displayAccountInfo();

System.out.println();

// Create a SavingsAccount object


SavingsAccount account2 = new SavingsAccount("Bob", 2000, 5); // 5%
interest rate
account2.displayAccountInfo();
account2.applyInterest();
account2.displayAccountInfo();
}
}

You might also like