[Read] Some comparisons between the instance constructor and the Type constructor

Source: Internet
Author: User

Article by: http://www.cnblogs.com/top5/archive/2009/10/31/1593706.html

The instance constructor is the instance constructor, And the Type constructor is the static constructor.

(1) In the instance constructor, We can initialize the instance fields and static fields of the class.

Public class Test
{
Private int m;
Private static int n;
Public Test ()
{
M = 1; // equivalent to this. m = 1;
N = 2; // The access between the instance field and the static field is no different.
}
}

(2) In the Type constructor, we can only initialize static fields for the purpose.

Public class Test
{
Private static int n = 1;
Static Test ()
{
N = 2;
// Is the final value of n 1 or 2? The sequence is first initialized to 1, and then assigned to 2 by the Type constructor.
}
}

(3) The conditions triggered by the instance constructor and the Type constructor are different.
The instance constructor is called when an instance of a class is constructed. The Type constructor is called when the class is accessed for the first time.
So it can be said that if an instance constructor of a class is called, its Type constructor will certainly be called (if any), and vice versa.

Public class Test
{
Public static int m;
Public Test ()
{
Console. WriteLine ("instance constructor ");
}
Static Test ()
{
Console. WriteLine ("Type constructor ");
}
}
Public class App
{
Static void Main ()
{
Test. m = 1;
// At this time, the Test class is accessed for the first time, so the Type constructor is called. The output result is: "Type constructor"
Test test = new Test ();
// At this time, the Test class is not accessed for the first time, but an instance of the class is created, so the output result is: "instance constructor"
// If the first line of code above is removed, you should know the output result. Please practice it yourself. Well, it's better to use "# Develop!
}
}

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.