Java misunderstanding: static code blocks will be automatically executed when classes are loaded ?, Java misunderstanding

Source: Internet
Author: User

Java misunderstanding: static code blocks will be automatically executed when classes are loaded ?, Java misunderstanding
Is the JAVA static code block automatically executed when the class is loaded?

Many Java developers have been deeply attacked by this idea for n times, and more people have been attacked by blogs that spread this wrong idea on the Internet.

Such as: http://blog.csdn.net/leeyu35/article/details/7755304


Then our program proves that this sentence is wrong:

Class MyClass1 {static {// static block System. out. println ("static block") ;}} public class Main {Class [] classArray = {MyClass1.class // to reference this class, the Class must be loaded into the virtual machine }; public static void main (String [] args) {System. out. println ("hello word ");}}

Execution Result: "static bolck" is not output"


When will the static block be called? I have found an article to describe more detailed blogs.

Http://www.cnblogs.com/ivanfu/archive/2012/02/12/2347817.html




When to execute Java static code blocks

This class will be executed when it is called or instantiated for the first time.
The static code block is executed only once. It is generally used to initialize some values and is globally shared among all objects.

Java static code block class loading sequence

The reason is one sentence: If you have a father, you will have a son!
When running the program, Load the AB class. Because A is A subclass of B, Load B first, and add it to class A LoadA. when calling the A = new A () code, will first call the constructor of the parent class B Create B and then call the constructor Create A of

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.