Java Reference
In-Depth Information
A bank account holds the balance in the account. The above definition of the
Account
class does just that. In the
real world, a bank account can hold many more pieces of information, for example, account number, account holder
name, address, etc. Let's keep the
Account
class simple so you can focus on the discussion of access levels. It allows
its every instance to hold a numeric value in its
balance
instance variable. If you want to create an instance of the
Account
class and manipulate its balance, it will look like this:
// Create an account object
Account ac = new Account();
// Change the balance to 1000.00
ac.balance = 1000.00;
// Change the balance to 550.29
ac.balance = 550.29;
This snippet of code can be executed anywhere in a Java application because both the
Account
class and its
balance
instance variable are
public
. However, in the real world, no one would let his bank account be manipulated
like this. For example, a bank may require you to have a minimum balance of zero in your account. With the above
implementation, nothing stops you from executing the following statement, which reduces the balance in an account
to a negative number:
// Set a negative balance
ac.balance = -440.67;
In object-oriented programming, as a rule of thumb, the pieces of information that define the state of an object
should be declared
private
. All instance variables of a class constitute the state of objects of that class. Therefore,
they should be declared
private
. If code outside a class is needed to have access to a
private
instance variable, the
access should be given indirectly, by providing a method. The method should have an appropriate access level, which
will allow only intended client code to access it. Let's declare the
balance
instance variable as
private
. The modified
code for the
Account
class is as follows:
// Account.java
package com.jdojo.cls;
public class Account {
private double balance;
}
With the modified
Account
class, you can create an object of the
Account
class anywhere in a Java application.
// Create an account object
Account ac = new Account();
However, you cannot access the
balance
instance variable of the
Account
object unless you write the code inside
the
Account
class itself. The following code is valid only if the code is written inside the
Account
class because the
private
instance variable
balance
cannot be accessed from outside the
Account
class:
// Change the balance
ac.balance = 188.37;