Java Reference
In-Depth Information
In general, you want to minimize the use of static methods and fields. If you find
yourself using lots of static methods, then that's an indication that you may not have
found the right classes to solve your problem in an object-oriented way.
S ELF C HECK
14. Name two static fields of the System class.
15. Harry tells you that he has found a great way to avoid those pesky
objects: Put all code into a single class and declare all methods and
fields static . Then main can call the other static methods, and all of
them can access the static fields. Will Harry's plan work? Is it a good
idea?
356
357
A DVANCED T OPIC 8.3: Alternative Forms of Field
Initialization
As you have seen, instance fields are initialized with a default value ( 0 , false , or
null , depending on their type). You can then set them to any desired value in a
constructor, and that is the style that we prefer in this topic.
However, there are two other mechanisms to specify an initial value for a field.
Just as with local variables, you can specify initialization values for fields. For
example,
public class Coin
{
. . .
private double value = 1;
private String name = "Dollar";
}
These default values are used for every object that is being constructed.
There is also another, much less common, syntax. You can place one or more
initialization blocks inside the class definition. All statements in that block are
executed whenever an object is being constructed. Here is an example:
public class Coin
Search WWH ::




Custom Search