Java Rules Initialization

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.