现在的位置: 首页 > 综合 > 正文

的区别

2018年12月12日 ⁄ 综合 ⁄ 共 1043字 ⁄ 字号 评论关闭

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

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

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


import java.util.*;

class ParentTest {
	static int y = 2;
	int yy = 3;
	
	static {
		
		System.out.println("parentTest y = " + y);
	}
	{
		++y;
	}
	
	ParentTest() {
		System.out.println("ParentTest construction y = " + y);
	}
}

public class Test extends ParentTest{

	/**
	 * @param args
	 */
	static int x = 1;
	static String s = "123";
	
	static {
		if (s.equals("123"))
			s = "345";
		if (x == 1) {
			x = 2;
		}
	}
	
	{
		System.out.println("<init>");
		if (s.equals("345"))
			s = "678";
		if (x == 2)
			x = 3;
		++x;
	}
	
	public Test() {
		System.out.println(x);
		System.out.println(s);
	}
	
	public Test(String ss) {
		System.out.println(x);
		System.out.println(s);
	}
	
	
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new Test();
		System.out.println();
		new Test("sssss");
		//Test t = new Test("333");
		//System.out.println(t.x);
		//System.out.println(Test.s);
	}

}

output:

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

ParentTest construction y = 4
<init>
5
678

抱歉!评论已关闭.