Java constructs code blocks, differences between constructors and normal functions, and invocation times

Source: Internet
Author: User

Here we talk about building blocks of code, the difference between constructors and normal functions, and the invocation time.
Building blocks of code: run at the earliest, which is better than the time the constructor is running, just as the constructor does when the object is initialized.
Constructors: Run time is later than building blocks of code, and is also run at object initialization time. There is no return value, and the constructor name and class name match.
Normal function: cannot be called automatically, need object to call, for example A.add ();
If you just look at the sequence of code execution: construct code blocks > Constructors > Normal functions
The following gives a program

1  Public  classTest1 {2 3      Public Static voidMain (string[] args) {4Code n=Newcode ();5 n.normal ();6         7     }8 }9 classcode{Ten     //Construct code block 1: One     { ASystem.out.println ("I am Building code block 1"); -     } -     //Constructor 1 the      Publiccode () { -System.out.println ("I am a constructor 1"); -     } -     //Constructor 2 +      PublicCodeintt) { -System.out.println ("I am a constructor 2" +t); +     } A     //Common Functions at      Public voidNormal () { -System.out.println ("I am a normal function"); -     } -     //Construct code block 2: -         { -System.out.println ("I am Building code block 2"); in         } -}

Operation Result:


By running the results from the program above, we can see that the construction code block is run first, regardless of whether it is constructed after the constructor or before the constructor function.
Then run the constructor. Constructors are overloaded with two types of initialization, one with no parameters and one with parameters.
If you do not call the normal function, the normal function cannot be executed.

Java constructs code blocks, differences between constructors and normal functions, and invocation times

Related Article

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.