Java static code block class load order problem.

Source: Internet
Author: User



Public B () {
System.out.println ("Create B");}
Class A extends B {
static {System.out.println ("Load A");}
Public A () {
System.out.println ("Create A");}
public class Test {
public static void Main (string[] args) { A A = new A ();
}

The answer is Load b-->load a-->create b-->create A;

The reason is a sentence: the first father, will have a son! When the program runs, load AB two classes, because A is a B subclass, so first load class B, load B, plus in Class A Loada,
When you call a = new A () code, the construction method of its parent class B is called first to create B and then to construct a
Ask:
The first father has a son, this sentence is not only for the "building object", he also for "class loading"? My understanding is: for the construction of objects,
It is true that the parent class object should be constructed before the subclass object can be constructed. But for classes to load,
, shouldn't you see which class should be loaded in memory that is missing?
Chase Answer:
Load the same time, when loading Class A, found that there is a parent class B, to search and load B,
The static blocks in a are not loaded at this time, and when B is loaded, it is returned to load a.
Only then does the program know what is going on in a, because there is a way to inherit from B.
If a is loaded first, then there are two cases, one of which is not inherited from a,
The other is to load B and then load a inherited from the method, then this Java is too bad, you say?

Java static code block class load order problem.

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.