What happens if you want to assign an initial value to a variable? One of the most straightforward ways to do this is to define variables within a class and assign values to them (note that this is not possible in C + +, although beginners in C + + always "want to"). Below, the field definitions within the measurement class have changed, providing an initial value:
Class Measurement {
Boolean b = true;
char c = ' x ';
byte B =;
Short s = 0xff;
int i = 999;
Long L = 1;
float f = 3.14f;
Double d = 3.14159;
//. . .
You can also initialize objects of a non basic (primary) type in the same way. If depth is a class, then you can insert a variable and initialize it as follows:
Class Measurement {
Depth o = new Depth ();
Boolean B = true;
// . . .
If you haven't already specified an initial value for O, and you're desperate to try it out in advance, you'll get a run-time error that tells you that an error has been generated (detailed in chapter 9th), which is called an "Exception".
You can even provide an initial value by calling a method:
Class Cinit {
int i = f ();
//...
}
Of course, this method can also use the arguments, but those arguments cannot be other class members that have not yet been initialized. Therefore, it is lawful to do the following:
Class Cinit {
int i = f ();
Int J = g (i);
//...
}
But it is illegal to do the following:
Class Cinit {
Int J = g (i);
int i = f ();
//...
}
This is where the compiler is not comfortable with the forward reference because it is related to the order of initialization, not to how the program is compiled.
This initialization method is very simple and intuitive. One of its limitations is that each object of type measurement will get the same initialization value. Sometimes this is what we want, but sometimes we need to look forward to greater flexibility.