In todays class we done a simple Java program that models a basic bank account. Using object-oriented programming (OOP) concepts, this program allows us to create bank accounts, deposit money, withdraw money, and display the account details.
Full Code
public class BankAccount{
int accountNumber;
String holderName;
int balance;
public BankAccount(int accountNumber,String holderName, int balance)
{
this.accountNumber = accountNumber; //Instance variables: accountNumber, holderName, balance
this.holderName = holderName; //Constructor to initialize account
this.balance = balance;
}
public static void main(String[] args)
{
BankAccount a1 = new BankAccount(12345,"Tamil",200); //obj1
a1.deposit(300); //method calling statements
int currentBalance1 = a1.balance; //storing return variable
a1.displayBalance();
a1.withdraw(100);
a1.displayBalance();
BankAccount a2 = new BankAccount(67890,"selvan",400); //obj2
a2.deposit(200); //method calling statements
int currentBalance2 = a2.balance;
a2.displayBalance();
a2.withdraw(150);
a2.displayBalance();
}
public int deposit(int amount)
{
balance = balance + amount; //it returns balance so int datatype is used
return balance;
}
public void withdraw(int amount) //it doesnot return anything so used void
{
balance = balance - amount;
}
public void displayBalance()
{
System.out.println("Account Number: " + accountNumber);
System.out.println("Account Holder: " + holderName);
System.out.println("Current Balance: " + balance);
}
}
1. Class and Instance Variables
The class BankAccount defines three variables:
- accountNumber: stores the unique account number.
- holderName: stores the name of the account holder.
- balance: stores the current account balance.
2. Constructor
The constructor initializes the values for a new bank account:
BankAccount a1 = new BankAccount(12345, "Tamil", 200);
3. deposit() Method
The deposit method adds the given amount to the balance:
a1.deposit(300); // Balance becomes 500
4. withdraw() Method
The withdraw method subtracts the given amount from the balance:
a1.withdraw(100); // Balance becomes 400
5. displayBalance() Method
This method prints the account number, holder name, and current balance:
a1.displayBalance();
6. main() Method
In the main method:
- Two bank accounts (a1 and a2) are created.
- Deposit and withdraw operations are performed.
- Updated account details are displayed after each transaction.
Output
Account Number: 12345
Account Holder: Tamil
Current Balance: 500
Account Number: 12345
Account Holder: Tamil
Current Balance: 400
Account Number: 67890
Account Holder: selvan
Current Balance: 600
Account Number: 67890
Account Holder: selvan
Current Balance: 450
Top comments (0)