Java Reference
In-Depth Information
2575
author
title
price
pages
binding
inStock
2575
2599
b
Figure 2-1. An instance of a Book object
As a shortcut, we can declare b and create a book object in one statement, like this:
Book b = new Book();
It is a common error to think that the Book variable b can hold a Book object. It cannot; it can hold only a reference
to a Book object. (In a similar manner, we should be familiar with the idea that a String variable does not hold a
string but, rather, the address of where the string is stored.) However, where the distinction (between an object and a
reference to the object) does not matter, we will speak as if b holds a Book object.
Once an object b is created, we can refer to its instance fields like this:
b.author b.title b.price
b.pages b.binding b.inStock
However, we can do so from outside the class only if the fields are declared public . We will see later how to access
the fields indirectly when they are declared private .
When an object is created, unless we say otherwise, its instance fields are initialized as follows:
0 .
Numeric fields are set to
'\0' (Unicode '\u0000' , to be precise).
Character fields are set to
false .
Boolean fields are set to
null . (A variable with the value null means that it does not reference or
Object fields are set to
point to anything.)
In our example, the following happens:
b.author (of type String ) is set to null ; remember that String is an object type.
b.title (of type String ) is set to null .
b.price (of type double ) is set to 0.0 .
b.pages (of type int ) is set to 0 .
b.binding (of type char ) is set to '\0' .
b.inStock (of type boolean ) is set to false .
We could specify an initial value when we declare an instance variable. Consider this code:
public class Book {
private static double Discount = 0.25;
private static int MinBooks = 5;
Search WWH ::




Custom Search