009-001-007

Access Control: Private Fields

Hard

Problem Description

Access Control: Private Fields

Learning Objective: Understand how to hide fields from external access using private modifier and access only through methods

Overview

Create a BankAccount class and define balance as a private field. Allow getting balance and making deposits only through methods.

Specifications

  • Define following in BankAccount class
    • private int balance field
    • public void deposit(int amount) method (add to balance)
    • public int getBalance() method (return balance)
  • Execute following in main method
    • Create BankAccount instance
    • Deposit with deposit(1000)
    • Get balance with getBalance() and output as "Balance: balance"

Output Format

Balance: 1000

Ready to Try Running Code?

Log in to access the code editor and execute your solutions for this problem.

Don't have an account?