Java Reference
In-Depth Information
14. During execution of the BankAccountTester program in the
preceding section, how many instance fields, local variables, and
parameter variables were created, and what were their names?
C OMMON E RROR 3.1: Forgetting to Initialize Object
References in a Constructor
Just as it is a common error to forget to initialize a local variable, it is easy to
forget about instance fields. Every constructor needs to ensure that all instance
fields are set to appropriate values.
106
107
If you do not initialize an instance field, the Java compiler will initialize it for you.
Numbers are initialized with 0, but object referencesȌsuch as string variablesȌ
are set to the null reference.
Of course, 0 is often a convenient default for numbers. However, null is hardly
ever a convenient default for objects. Consider this Ȓlazyȓ constructor for a
modified version of the BankAccount class:
public class BankAccount
{
public BankAccount() {} // No statements
. . .
private double balance;
private String owner;
}
The balance is set to 0, and the owner field is set to a null reference. This is a
problemȌit is illegal to call methods on the null reference.
If you forget to initialize a local variable in a method, the compiler flags this as an
error, and you must fix it before the program runs. If you make the same mistake
with an instance field in a class, the compiler provides a default initialization, and
the error becomes apparent only when the program runs.
To avoid this problem, make it a habit to initialize every instance field in every
constructor.
Search WWH ::




Custom Search