服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

java 程序初始化过程详解

觉得core java在java 初始化过程的总体顺序没有讲,只是说了构造器时的顺序,作者似乎认为路径很多,列出来比较混乱。我觉得还是要搞清楚它的过程比较好。所以现在结合我的学习经验写出具体过程:

  过程如下:

  1.在类的声明里查看有无静态元素(static element, 我姑且这么叫吧),比如:

static int x = 1,
{
 //block
 float sss = 333.3; string str = "hello";
}

  或者 比如

static {
 //(static block),
 int x = 2;
 double y = 33.3;
}

  如果有static element则首先执行其中语句,但注意static element只执行一次,在第二次创建类的对象的时候,就不会去执行static element的语句.

  2.查看此类是否为启动运行类,若为启动运行类,则执行main()方法里的语句对应语句

  3.若不是启动运行类,则按代码的排版先后顺序继续执行非static element的变量赋值以及代码块.

  4.最后执行构造方法,如果在被调用的构造方法里面有this关键字(注意,如果你考虑要调用其他构造方法,则应该把this写在最前面,不然会产生错误),则先调用相应构造方法主体,调用完之后再执行自己的剩下语句.

/** *//**
*
* @author livahu
* created on 2006年9月6日, 下午17:00
*/
class firstclass ...{
 firstclass(int i) ...{
  system.out.println("firstclass(" + i + ")");
 }

 void usemethod(int k) ...{
  system.out.println("usemethod(" + k + ")");
 }
}

class secondclass ...{
 static firstclass fc1 = new firstclass(1);
 firstclass fc3 = new firstclass(3);
 static ...{
  firstclass fc2 = new firstclass(2);
 }

 ...{
  system.out.println("secondclass's block, this block is not static block.");
 }

 secondclass() ...{
  system.out.println("secondclass()");
 }
 firstclass fc4 = new firstclass(4);
}

public class initiationdemo ...{
 secondclass sc1 = new secondclass();
 ...{
  system.out.println("hello java world!");
 }

 public static void main(string[] args) ...{
  system.out.println("inside main()");
  secondclass.fc1.usemethod(100);
  initiationdemo idobj = new initiationdemo();
 }
 static secondclass sc2 = new secondclass();
}

  运行结果:

firstclass(1)
firstclass(2)
firstclass(3)
secondclass's block, this block is not static block.
firstclass(4)
secondclass()
inside main()
usemethod(100)
firstclass(3)
secondclass's block, this block is not static block.
firstclass(4)
secondclass()
hello java world!

扫描关注微信公众号