Java Reference
In-Depth Information
For example, the following
Apple
class uses explicit initialization to initialize its
variety
fi eld:
1. public class Apple extends Fruit {
2. public String variety = “McIntosh”;
3.
4. public Apple(String variety) {
5. System.out.println(“Constructing an Apple”);
6. this.variety = variety;
7. }
8. }
The
variety
fi eld is assigned the value
“McIntosh”
after the memory is zeroed by the
new
operator. That means that
variety
was actually
null
for a brief moment before it was
assigned
“McIntosh”
.
Explicit initialization allows you to initialize a fi eld before a constructor is executed.
However, the most common reason for using explicit initialization is simply that sometimes
it is just easier to initialize a fi eld when you declare it, especially if the initialization is the
same for every instance of the class.
In the previous example, setting the
variety
fi eld of all
Apple
objects to initially be
“McIntosh”
probably does not make sense in a real-world application. However, there are
plenty of situations where explicit initialization comes in handy. For example, the following
Movie
class has a
Vector
fi eld that contains
Fan
objects:
1. import java.util.Vector;
2.
3. public class Movie {
4. public Vector<Fan> fans = new Vector<Fan>();
5. public String title;
6. public double boxOfficeTotal;
7.
8. public Movie(String title) {
9. this.title = title;
10. }
11.
12. public void addFan(Fan f) {
13. fans.add(f);
14. }
15.}
Because the
Vector
has the same initial value for all instances of the
Movie
class, using
explicit initialization makes sense and simplifi es the constructor code. If the
Movie
class
had multiple constructors, we would have to make sure that the
Vector
gets instantiated
in each constructor. By using explicit initialization, we are ensured that the
fans
fi eld is
Search WWH ::
Custom Search