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

Java Ex4

java exercise 4

Uploaded by

TRANAND TR
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Java Ex4

java exercise 4

Uploaded by

TRANAND TR
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Ex.

4 – Program to demonstrate static members and methods

Aim
To demonstrate static members and methods.

Algorithm
Step 1: Define a class named BankAccount with accountHolder and balance as
its non-static members, and totalAccounts as a static member.
Step 2: Define a constructor to initialize the account holder and their balance,
and to increment totalAccounts.
Step 3: Define a non-static method named displayAccountDetails() to display
the account details.
Step 4: Define a static method named displayTotalAccounts() to display the
number of accounts created.
Step 5: Create two different instances of the BankAccount class and invoke
both the static and non-static methods.

Source Code
class BankAccount
{
static int totalAccounts = 0; // Static variable to count total accounts

String accountHolder;
double balance;

BankAccount(String accountHolder, double balance)


{
this.accountHolder = accountHolder;
this.balance = balance;
totalAccounts++;
}

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

static void displayTotalAccounts() //static method definition


{
System.out.println("Total bank accounts created: " + totalAccounts);
}
}

MyClass.java
class MyClass
{
public static void main(String[] args)
{
BankAccount account1 = new BankAccount("Anand", 1500.00);
BankAccount account2 = new BankAccount("Arun", 2500.00);

account1.displayAccountDetails();
account2.displayAccountDetails();

BankAccount.displayTotalAccounts(); // Display total accounts using static method


}
}

You might also like