Java Reference
In-Depth Information
Warning Static methods can cause problems. Suppose you have two threads, each of which is working with
an object whose class definition has a static method. If both classes try to access the method at the same time,
bad things can happen. For one thing, any fields modified by the method can end up with the wrong value,
because the threads might run in the wrong order. Also, a static method has just one instance (the class itself), so
a class that takes a long time to do whatever it does can keep the second (and third, fourth, and so on) thread
waiting.
Constructors
The AverageImpl class includes a constructor, as shown in Listing 2-11.
Listing 2-11. A constructor
public AverageImpl(int[] ints) throws IllegalArgumentException {
if (ints.length == 0){
throw new IllegalArgumentException(EXCEPTION_MESSAGE);
}
this.ints = ints;
}
Constructors look like methods but aren't. Notice the lack of a return type and the name being
identical to the class name. They are called when we first create an object and enable us to set up the
object before we do anything with it. Creating the object is called instantiation .
What needs to be done varies tremendously by class. Many constructors (such as the one shown in
this example) set some values. Other classes might create other objects, open a database connection or a
file, or start some other process (and the possibilities don't stop there).
If you don't define a constructor, Java still creates a default constructor, to enable the new keyword
to work. Otherwise, no one would ever be able to create an instance of your class. Constructors can have
all the usual access modifiers.
You can also create multiple constructors for a single class. For example, suppose we want to
provide a handy way to average any other number with 2. We can do that with a constructor such as in
Listing 2-12:
Listing 2-12. Another constructor
public AverageImpl(int otherNumber) {
ints = new int[] {2, otherNumber};
}
Now we have two ways to create an instance of the AverageImpl class.
Note The this keyword is a reference to the object the class defines. In this case, the this keyword is
necessary to distinguish the ints field in the class from the ints argument in the constructor's argument list.
Search WWH ::




Custom Search