Blind Zone generated when initializing static members

Source: Internet
Author: User

Static members belong to Classes rather than instances. Static members have a wide range of applications. For example, public static member values can be obtained or set globally in an application, which is similar to the global variables of C ++, however, improper use may also cause problems.

Class Test
{
Private Static string strstaticname = "hello ";
// No parameter Constructor
Public test ()
{
}
// Parameter Constructor
Public test (string strname)
{
Strstaticname = strname;
}

Public String getname ()
{
Return strstaticname;
}

}

Static void main (string [] ARGs)
{
Console. writeline ("when you create a T1 instance, set the name to Oriental ");
// Create instance T1
Test T1 = new test ("oriental ");
Console. writeline ("so the name obtained using the getname method is: {0}", t1.getname ());
Console. writeline ("");

// Create instance T2
Console. writeline ("when creating T2 instance, the name is not set ");
Test t2 = new test ();
String strname = t2.getname ();
Console. writeline ("but the name obtained through the getname method is: {0}", strname );
Console. Read ();

}

After debugging:

Analysis: in an application, no matter how many instances of a class are created, the static fields of the class are initialized only once.

Solution: 1) Cancel static keyword static

2) All constructors with parameters are used.

3) assign values to static fields in the no-argument Constructor

Public test ()

{

Strstaticname = "hello ";

}

Blind Zone generated when initializing static members

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.