看大家这么热情我也来谈谈我的看法
首先我认同,如果带main()的类没有被new 是不会执行构造方法的。
有人说main()是最先执行的,其实如果你看了《core java》你会发现static initialization block是最先执行的,他有个例子如下:
public class Hello
{
static
{
System.out.println("Hello, World");
System.exit(0);
}
}
这样一个应用程序就能在没有main()的情况下输出一行字到控制台。
其实静态初始化块也属于类的初始化的一部份,他负责初始化静态变量,他是在类第一次被调用的时候被调用。下面是《core java 7》原话:
==================================================
You initialize a static field either by supplying an initial value or by using a static initialization block. You have already seen the first mechanism:
static int nextId = 1;
If the static fields of your class require complex initialization code, use a static initialization block.
==================================================
另外再提一下对象的初始化,也就是调用构造方法的时候,java的处理过程(注意与类的初始化分开)。
1.All data fields are initialized to their default value (0, false, or null).
2.All field initializers and initialization blocks are executed, in the order in which they occur in the class declaration.
3.If the first line of the constructor calls a second constructor, then the body of the second constructor is executed.
4.The body of the constructor is executed.
下面是对上面的话的一些解释,本人英语水平有限,翻译和解释有错的地方请大家指导。
1.所有数据都被初始化成他的默认值(0, false, or null)
2.所有数据初始化(也就是你定义的全局变量:private int i=5;),所有的初始化块被调用。
3.如果构造器的第一行调用第二个构造器,那么第二个构造器被调用。
4.构造器被调用。