0%
0 / 10 answered

Class Variables and Methods Practice Test

10 Questions
Question
1 / 10
Q1

How does the static method interact with the class variable in this code?


// BankAccount demonstrates class variables (static) and class methods (static).

public class BankAccount {

    // Class variable shared by all accounts in the bank.

    private static double bankTotalBalance = 0.0;

    // Instance variable unique to each BankAccount object.

    private double accountBalance;

    // Constructor initializes an account with an opening deposit.

    public BankAccount(double openingDeposit) {

        accountBalance = openingDeposit;

        // Update the class-level total whenever an account is created.

        bankTotalBalance += openingDeposit;

    }

    // Static (class) method returns the total balance across all accounts.

    public static double getBankTotalBalance() {

        return bankTotalBalance;

    }

    // Instance method deposits money into this account and updates the class total.

    public void deposit(double amount) {

        accountBalance += amount;

        bankTotalBalance += amount;

    }

    // Instance method withdraws money from this account and updates the class total.

    public void withdraw(double amount) {

        accountBalance -= amount;

        bankTotalBalance -= amount;

    }

    // Main method demonstrates creating accounts and adjusting balances.

    public static void main(String[] args) {

        BankAccount a = new BankAccount(100.0);

        BankAccount b = new BankAccount(50.0);

        a.deposit(25.0);

        b.withdraw(10.0);

        System.out.println(BankAccount.getBankTotalBalance());

    }

}

Question Navigator