欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

有关初始化的问题3

程序员文章站 2022-05-21 21:08:00
...
package com.wang.util;

public class Mugs {
	
	Mug mug1;
	Mug mug2;
	{
		mug1=new Mug(22);
		mug2=new Mug(33);
		System.out.println("mug1 & mug2 initialized");
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("inside main()");
		new Mugs();
		System.out.println("new Mugs() completed");
		new Mugs();
		System.out.println("new Mugs() completed");

	}

}


class Mug{
	Mug(int maker){
		System.out.println("Mug("+maker+")");
	}
	
	void f(int maker){
		System.out.println("f("+maker+")");
	}
}

output:

inside main()
Mug(22)
Mug(33)
mug1 & mug2 initialized
new Mugs() completed
Mug(22)
Mug(33)
mug1 & mug2 initialized
new Mugs() completed

 

每new一次就来一次。

相关标签: 类初始化 java