In: Computer Science
Create a new class called Account with a main method that contains the following:
• A static variable called numAccounts, initialized to 0.
• A constructor method that will add 1 to the numAccounts variable each time a new Account object is created.
• A static method called getNumAccounts(). It should return numAccounts.
Test the functionality in the main method of Account by creating a few Account objects, then print out the number of accounts
SOLUTION
I am giving the implementation in 2 languages . The first one is C++.
Code:
#include <iostream>
using namespace std;
static int numAccounts = 0;
class Account
{
public:
Account()
{
numAccounts += 1;
}
};
static int getNumAccounts()
{
return numAccounts;
}
int main(int argc, char const *argv[])
{
Account a1;
Account a2;
cout << getNumAccounts()<<"\n";
return 0;
}
______________________________________________________________________________________________________
OUTPUT:
JAVA code :
class Account {
static int numAccounts = 0;
static int getNumAccounts(){
return numAccounts;
}
//constructor
Account(){
numAccounts += 1;
}
public static void main(String[] args) {
//testing the Class
Account a1 = new Account();
System.out.println(getNumAccounts());
Account a2 = new Account();
Account a3 = new Account();
System.out.println(getNumAccounts());
}
}
OUTPUT:
comment if any doubt