Java class loading and initialization

Source: Internet
Author: User

First paragraph:

Class a{Public A () {this.list ();  } public void list () {System.out.println (' in a list. '); }} class B extends a{private final static B instance = new B ();//The list is called at the end of the construction, but there is no wrong public static B get    Instance () {System.out.println ("getting Instance B..");  return instance;  } public void list () {System.out.println ("in B List ...");  }} public class Loadclasserrordemo {public static void main (string[] args) {b.getinstance (); }} running result: inbList...getting instance B.. Results analysis: the getinstance () method to obtain class B instances need to load Class B, the process of loading need to call the construction method of Class B, the construction method of Class B first call the Class A construction method, A's construction method needs to use the list method, but the method in Class B has been overloaded, So the real call is the list of Class B. This design is problematic, Class A as a class that can be inherited, but it is not expected to be inherited by the class, and can not control the subsequent sub-class to the list modification, is the upper layer of code relies on the underlying code of the serious design vulnerability. Modified by: 1 The list method of Class A is not disclosed, that is, PRIVATE;2 will split the construction method of Class A, the dynamic part and the static part, the static in its own set and closed, dynamic support expansion; 3 This should be a design for the abstract class, so that the subclass to complete its own list method, But it does not offer itself. Second paragraph:Class a{Public A () {this.list ();  } public void list () {System.out.println (' in a list. '); }} class B extends a{private final static B instance  = new B ();//The list is called here, and the public static is called when the structure is not finished.    b getinstance () {System.out.println ("getting instance B..");  return instance;    } public void list () {System.out.println ("in B List ...");    try{Thread.Sleep (1000);    }catch (Exception e) {e.printstacktrace ();  } instance.list2 (); } public void List2 () {}} public class Loadclasserrordemo {  public static void Main (string[] args) {new Th        Read () {public void run () {try{thread.sleep (1000);        }catch (Exception e) {e.printstacktrace ();      } b.getinstance (). List2 ();  }}.start (); }}  Run Result: in B list ... Exception in Thread "Thread-0" Java.lang.ExceptionInInitializerErrorat Chapter03.load.loadclasserrordemo$1.run ( LOADCLASSERRORDEMO.JAVA:42) caused by:java.lang.NullPointerExceptionAt Chapter03.load.b.list (loadclasserrordemo.java:26) at CHAPTER03.LOAD.A. (Loadclasserrordemo.java:4) at chapter03.load.b. (loadclasserrordemo.java:11) at chapter03.load.b. (loadclasserrordemo.java:12) ... 1 more  Description: When calling Class A constructor method, the list method of Class B is used, and the list method of Class B needs to call instance's List2 method before calling to ensure that the instance instance has been generated. However, instance must not be valid until Class B is loaded and initialized, so it cannot be called. There is no problem with changing the list method of a to private, which causes the instance not to be generated. The loading of the   class is divided into 3 parts: Read the file, from the parent to the child's ClassLoader load, the multiple paths are not found in the throw classnotfoundexception; Link, the byte code to parse, check, do not conform to the standard is thrown classnotfounderror; Initialize, call the class object's own constructor, static variable, and static block assignment. All classes must be loaded and initialized before use, and if multiple threads try to access the class at the same time, they must wait for the static block to complete, otherwise they will block. So the code in static should not be too much, especially IO operation, otherwise the blocking time may be very long.   simply write down the Java initialization: 1 The local variable must be initialized before it is used, but if the member of the class declares that there is a default value if the value is not given, the handle is null (think of the reason: Each method of the class may initialize or use an object variable, the object must be set before the value of science); 2 Automatic initialization and assignment initialization are not affected by constructors: class Counter {

int i;
Counter () {i = 7;}

}//This will first set the value of I to 0 and then call the constructor I to assign a value of 7
class a2{int v;  Loadclasserrordemo l;    Public A2 () {F1 ();    X=y;  System.out.println ("In the End v=" +v);    } void F1 () {System.out.println ("in Method F1 v=" +v);  System.out.println ("in Method l=" +l);  } void F2 (int x) {System.out.println (x);  }}public class Inittest {public static void main (string[] args) {new A2 (); }} Run Result: In method F1 v=0in method L=nullin the end v=7 3initialization of a static data member (partly from the Java programming Idea): If the data is static, if it belongs to a primitive type (the primary type) and does not initialize it, it automatically obtains its own standard primitive type initial value, if it is a handle to an object, Then, unless you create a new object and connect the handle to it, you will get a null value (NULL). If you want to initialize at the same time as defined, the method taken is the same as the non-static value surface. However, because the static value has only one storage area, no matter how many objects are created, you will inevitably encounter the question of when to initialize that storage area. class Bowl {  Bowl (int marker) {System.out.println ("Bowl (" + marker + ")");  } void f (int marker) {System.out.println ("f (" + marker + ")");  }}class Table {static Bowl B1 = new Bowl (1);    Table () {System.out.println ("table ()");  B2.F (1);  } void F2 (int marker) {System.out.println ("F2 (" + marker + ")"); } static Bowl b2 = new Bowl (2);}  Class Cupboard {Bowl B3 = new Bowl (3);  static Bowl b4 = new Bowl (4);    Cupboard () {System.out.println ("cupboard ()");  B4.F (2);  } void F3 (int marker) {System.out.println ("F3 (" + Marker + ")"); } static Bowl B5 = new Bowl (5);} public class Staticinitialization {public static void main (string[] args) {System.out.println ("Creating New cupboard    () in main ");    New Cupboard ();    System.out.println ("Creating New Cupboard () in main");    New Cupboard ();    T2.F2 (1);  T3.F3 (1);  } static Table t2 = new Table (); static cupboard T3 = new cupboard ();} :~  operation Result: Bowl (1) Bowl (2) Table () f (1)Bowl (4)Bowl (5)Bowl (3)Cupboard () F (2) Creating new Cupboard () in mainBowl (3)Cupboard () F (2) Creating new Cupboard () in mainBowl (3)Cupboard () F (2) F2 (1) F3 (1) loading the Staticinitialization class first requires loading two static object T2,t3, Loading non-static members T3 found that B3 was initialized after loading B4 and B5 (think about the static members that are often needed by non-static members), and Bowl (3) appeared 3 times, while Bowl (4), Bowl (5) appeared only once, Explains that each creation of a cupboard requires that a new B3 member be generated for it, and that the static members are shared. Sum up:The order of initialization is static first (if they have not been initialized by the previous object creation process), followed by non-static objects. Now consider a class named Dog:
(1) When an object of type dog is first created, or when the static method of the dog class is first accessed by the/static field, the Java interpreter must find Dog.class (search in the pre-set classpath).
(2) After Dog.class is found (it creates a class object), all of its static initialization modules will run. Therefore, static initialization occurs only once-when the Class object is first loaded.
(3) When creating a new dog (), the build process of the dog object will first allocate enough storage space for a dog object in the heap.
(4) This storage space is cleared to zero, and all the basic types in Dog are set to their default values (0 for numbers, and for Boolean and char equivalent settings).
(5) All initialization occurs when the field definition is performed.
(6) Executes the builder.

Java class loading and initialization

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.