Initialization methods in Java

Source: Internet
Author: User

This article is mainly about the "Java programming thought" to see things, is the seventh chapter of the beginning of the re-use of the class, mainly the class initialization of the location of several methods, mainly including

1. Where the object is defined. This means that they are always initialized before the constructor is called.

2. In the constructor of the class

3. This approach is called lazy initialization before you want to use these objects. This approach reduces the additional burden of generating objects that are not worthwhile and do not have to generate objects every time.

4. Use instance initialization.

Here are some examples of these four ways.

1 classsoap{2     PrivateString S;3 Soap () {4System.out.println ("Soap ()");5s = "constructed";//initializing in the constructor6     }7      PublicString toString () {8         returns;9     }Ten } One  A  Public classbath{ -     PrivateString S1 = "Happy", s2 = "Hello";//defining the local initialization of an object -     PrivateString S3, S4; the     PrivateSoap Castile; -     Private inti; -      PublicBath () { -Print ("Bath ()"); +S3 = "Tonny"; -     } +  A{i = 43;}//using instance initialization at  -      PublicString toString () { -         if(S4 = =NULL) -S4 = "John";//Lazy Initialization -         return"Done"; -     } in}

In Bath (), a line of statements is executed before all initialization is made, and if not initialized at the definition, there is no guarantee that the information will be initialized before it is sent to the object reference unless an unavoidable run-time exception occurs.

Initialization methods in Java

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.