类的初始化--各个构造函数和代码块实验

       创造类的时候,少不了参数和构造函数,也许还有代码块。下面有两个类,分别执行看看效果并分析。

       父类:

class parent{
	int p = 0;
	{
		p=1;
		System.out.println("parent----daimakuai    p="+p);
	}
	static {
		System.out.println("parent----static");
	}
	public parent(){
		System.out.println("parent------gouzao-- p ="+p);
	}
	public parent(String s){
		System.out.println("parent------gouzaos-- p ="+p);
	}
}

 子类:

class child extends parent{
	//下面的代码报错
//	{
//		c = 1;
//		System.out.println("child----daimakuai    c="+c);
//	}	
	static{
		System.out.println("child----static");
	}
	int c = 0;
	{
		c = 1;
		System.out.println("child----daimakuai    c="+c);
	}
	public child(){
		System.out.println("child------gouzao-- c ="+c);
	}
	public child(String s){
		System.out.println("child------gouzaos-- c ="+c);
	}
}

 第一次执行的main函数:

public static void main(String[] a){
		
		child c = new child("abc");
	}

 结果:

parent----static
child----static
parent----daimakuai    p=1
parent------gouzao-- p =1
child----daimakuai    c=1
child------gouzaos-- c =1

 可见,他的执行顺序是这样:  父类的static代码块-》子类的static代码块-》父类的普通代码块-》父类的默认构造函数-》子类的普通代码块-》子类的应该被调用的构造函数。在child中发现代码块中报错,这是因为代码块初始化类的参数的时候虽然可以在参数的上边,但是在编译的时候,jvm是按顺序编译的,所以会报错(个人观点,查资料未果)。

     如果把父类的默认构造函数去掉,那么子类的构造函数就会报错:Implicit super constructor parent() is undefined. Must explicitly invoke another constructor

     这是因为,在子类的构造函数里,会调用父类的构造函数。如果不指定,那么就会调用父类的默认的无参构造函数。而编辑器找不到无参构造函数怎么办?  报错。。。。

    在子类的两个构造函数里面加上指定的构造函数就不会报错了!

扫描二维码关注公众号,回复: 230685 查看本文章
public child(){
		//必须加在第一行
		super("");
		System.out.println("child------gouzao-- c ="+c);
	}
	public child(String s){
		super("");
		System.out.println("child------gouzaos-- c ="+c);
		
	}

继续执行main函数

public static void main(String[] a){
		parent p = new parent("abc");
		child c = new child("abc");
		child c1 = new child("abc");
	}

 结果:

parent----static
parent----daimakuai    p=1
parent------gouzaos-- p =1
child----static
parent----daimakuai    p=1
parent------gouzao-- p =1
child----daimakuai    c=1
child------gouzaos-- c =1
parent----daimakuai    p=1
parent------gouzao-- p =1
child----daimakuai    c=1
child------gouzaos-- c =1

 发现与第一次有些不同的是,static代码块里代码只执行了一次。

   static是java里面比较神奇的关键字,也是做工程时候最常用到的关键字之一。

猜你喜欢

转载自709002341.iteye.com/blog/2251458
今日推荐