Whether the constructor is called when Java calls a static function

Source: Internet
Author: User

When I look at "Think in Java" Today, there is a problem: whether the constructor of the class will be called when a static function is called. Do not find the relevant content on the Internet, try to test the results.

1  Public classTest {2      PublicTest () {3System.out.println ("constructor");4     }5      Public Static voidprint () {6System.out.println ("Static");7     }8      Public Static voidMain (string[] args) {9 test.print ();Ten     } One}

Results:

1 Static

As you can see, the result is only static, that is, the constructor is not executed.

At the beginning of this question, there is the initialization order, whether the static method is also initialized before the execution of it?

1  Packagetest;2 3  Public classTest {4     Static intI=1;5      PublicTest () {6System.out.println ("constructor");7     }8      Public Static voidprint () {9System.out.println (i+ "Static");Ten     } One      Public Static voidMain (string[] args) { A test.print (); -     } -}

Results:

1 1static

As you can see, the static variables have been initialized.

By flipping the book, Initialize the order:

Static variables, static initialization blocks > variables, initialization blocks > constructors

It is important to note that static functions cannot invoke non-static variables, which are for instance. The first code also shows that the constructor is not called after the static function is called.

Whether the constructor is called when Java calls a static function

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.