Static constructor, java static Constructor

Source: Internet
Author: User

Static constructor, java static Constructor

1. The static constructor is used to initialize static data or perform only one special operation.

2. The static constructor neither has an access modifier nor a parameter.

3. Before creating the first instance or referencing any static member, the static constructor is automatically called to initialize the class.

4. The static constructor cannot be called directly.

5. If a static constructor causes an exception, the constructor will not be called again during the runtime, And the type will remain uninitialized during the lifetime of the application domain where the program runs.

Class Program {static void Main (string [] args) {// call the static constructor after bus1 is instantiated. Only one Bus bus1 = new Bus (71) is called ); bus bus2 = new Bus (72); bus1.Drive (); System. threading. thread. sleep (3600); bus2.Drive (); Console. writeLine ("Press any key to exit. "); Console. readKey () ;}} public class Bus {protected static readonly DateTime globalStartTime; protected int RouteNumber {get; set;} static Bus () {globalStartTime = DateTime. now; Console. writeLine ("static constructor sets global start time to {0}", globalStartTime. toLongTimeString ();} public Bus (int routeNum) {RouteNumber = routeNum; Console. writeLine ("Bus # {0} is created", RouteNumber);} public void Drive () {TimeSpan elapsedTime = DateTime. now-globalStartTime; Console. writeLine ("{0} is starting its route {1: N2} minutes after global start time {2}", this. routeNumber, elapsedTime. totalMilliseconds, globalStartTime. toLongTimeString ());}}

  

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.