Java: What is the difference between and ?

前端 未结 4 1815
不知归路
不知归路 2020-12-02 08:11

I am unable to understand the following text... Does it mean that is for empty constructors? Why is important to have two different versions?

相关标签:
4条回答
  • 2020-12-02 08:39

    <init> is the (or one of the) constructor(s) for the instance, and non-static field initialization.

    <clinit> are the static initialization blocks for the class, and static field initialization.

    class X {
    
       static Log log = LogFactory.getLog(); // <clinit>
    
       private int x = 1;   // <init>
    
       X(){
          // <init>
       }
    
       static {
          // <clinit>
       }
    
    }
    
    0 讨论(0)
  • 2020-12-02 08:55

    <init> denotes a constructor, <clinit> denotes a static initializer: "Static Initialization Blocks" in the Java Tutorial, Static initializer in Java.

    0 讨论(0)
  • 2020-12-02 08:57

    Just to add If you use Class.forName method, it only intializes the class. So from within this method, it makes a call only to clinit and when you use newInstance on the object returned from forName, it will call init for the instance initialization. You can use below code to see it in debug.

    public class ByteCodeParent
    {
     public static String name="ByteCode";
     public ByteCodeParent()
    {
        System.out.println("In Constructor");
    }
    
     static
     {
         System.out.println("In Static");
     }
    
     {
         System.out.println("In Instance");
     }
    

    To test, use

       Class<ByteCodeParent> bcp2 =(Class<ByteCodeParent>) Class.forName("ByteCodeParent");
    ByteCodeParent bcp4= bcp2.newInstance();
    
    0 讨论(0)
  • 2020-12-02 09:03

    The difference between <init> and <clinit> is that <init> is used for constructor methods that initialise an object instance, whereas <clinit> is used to initialise the class object itself. For instance initialisation of any static class level fields is done in <clinit> when the class is loaded and initalised.

    0 讨论(0)
提交回复
热议问题