7.4. InitializersIt is possible to initialize the values of member variables in an initializer , instead of having to do so in the constructor. You create an initializer by assigning an initial value to a class member: private int Second = 30; // initializer Assume that the semantics of the Time object are such that no matter what time is set, the seconds are always initialized to 30. You might rewrite your Time class to use an initializer so that the value of Second is always initialized, as shown in Example 7-4. Example 7-4. Using an initializer
The output looks like this: 8/1/2008 9:35:30 If you do not provide a specific initializer, the constructor initializes each integer member variable to zero (0). In the case shown, however, the Second member is initialized to 30: private int Second = 30; // initializer Later in this chapter, you will see that you can have more than one constructor. If you assign 30 to Second in more than one of these, you can avoid the problem of having to keep all the constructors consistent with one another by initializing the Second member, rather than assigning 30 in each of the constructors. |