<init>与<clinit>的区别

在编译生成class文件时,会自动产生两个方法,一个是类的初始化方法<clinit>, 另一个是实例的初始化方法<init>

<clinit>:在jvm第一次加载class文件时调用,包括静态变量初始化语句和静态块的执行

<init>:在实例创建出来的时候调用,包括调用new操作符;调用Class或Java.lang.reflect.Constructor对象的newInstance()方法;调用任何现有对象的clone()方法;通过java.io.ObjectInputStream类的getObject()方法反序列化。

[java] view plain copy
 
  1. import java.util.*;  
  2.   
  3. class ParentTest {  
  4.     static int y = 2;  
  5.     int yy = 3;  
  6.       
  7.     static {  
  8.           
  9.         System.out.println("parentTest y = " + y);  
  10.     }  
  11.     {  
  12.         ++y;  
  13.     }  
  14.       
  15.     ParentTest() {  
  16.         System.out.println("ParentTest construction y = " + y);  
  17.     }  
  18. }  
  19.   
  20. public class Test extends ParentTest{  
  21.   
  22.     /** 
  23.      * @param args 
  24.      */  
  25.     static int x = 1;  
  26.     static String s = "123";  
  27.       
  28.     static {  
  29.         if (s.equals("123"))  
  30.             s = "345";  
  31.         if (x == 1) {  
  32.             x = 2;  
  33.         }  
  34.     }  
  35.       
  36.     {  
  37.         System.out.println("<init>");  
  38.         if (s.equals("345"))  
  39.             s = "678";  
  40.         if (x == 2)  
  41.             x = 3;  
  42.         ++x;  
  43.     }  
  44.       
  45.     public Test() {  
  46.         System.out.println(x);  
  47.         System.out.println(s);  
  48.     }  
  49.       
  50.     public Test(String ss) {  
  51.         System.out.println(x);  
  52.         System.out.println(s);  
  53.     }  
  54.       
  55.       
  56.       
  57.     public static void main(String[] args) {  
  58.         // TODO Auto-generated method stub  
  59.         new Test();  
  60.         System.out.println();  
  61.         new Test("sssss");  
  62.         //Test t = new Test("333");  
  63.         //System.out.println(t.x);  
  64.         //System.out.println(Test.s);  
  65.     }  
  66.   
  67. }  



output:

parentTest y = 2
ParentTest construction y = 3
<init>
4
678


ParentTest construction y = 4
<init>
5
678

原文地址:https://www.cnblogs.com/yaohaitao/p/5536302.html