Java运行程序代码段

发表于:2015-8-28 10:08

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:blfshiye    来源:51Testing软件测试网采编

  我记得那时候刚毕业。学习JAVA恐惧是这里,它是关于JAVA称号。我总是不正确。如今,这最后审查。看了好半天。得赶紧把刚才学习到的那点东西记下来。
  一、关于static的代码段运行顺序
package com.test;
/**
* Created with IntelliJ IDEA.
* User: 菜鸟大明
* Date: 14-6-15
* Time: 下午11:19
* To change this template use File | Settings | File Templates.
*/
class Mug {
Mug(int marker) {
System.out.println("Mug(" + marker + ")");
}
void f(int marker) {
System.out.println("f(" + marker + ")");
}
}
public class Mugs {
Mug c1;
Mug c2;
{
c1 = new Mug(1);
c2 = new Mug(2);
System.out.println("c1 & c2 initialized");
}
Mugs() {
System.out.println("Mugs()");
}
public static void main(String[] args) {
System.out.println("Inside main()");
Mugs x = new Mugs();
Mugs y = new Mugs();
}
}
  来自CODE的代码片
  snippet_file_0.txt
  运行结果例如以下:
  Inside main()
  Mug(1)
  Mug(2)
  c1 & c2 initialized
  Mugs()
  Mug(1)
  Mug(2)
  c1 & c2 initialized
  Mugs()
  二、关于非static得代码段运行顺序
package com.test;
/**
* Created with IntelliJ IDEA.
* User: 菜鸟大明
* Date: 14-6-15
* Time: 下午11:21
* To change this template use File | Settings | File Templates.
*/
class Cup {
Cup(int marker) {
System.out.println("Cup(" + marker + ")");
}
void f(int marker) {
System.out.println("f(" + marker + ")");
}
}
class Cups {
// 无论一个类创建了多少个对象,静态变量只有一个副本
static Cup c1;
static Cup c2;
// 静态块只在第一次被执行时初始化。
static {
c1 = new Cup(1);
c2 = new Cup(2);
}
Cups() {
System.out.println("Cups()");
}
}
class ExplicitStatic {
public static void main(String[] args) {
System.out.println("Inside main()");
Cups.c1.f(99); // (1)
}
// 先初始化静态变量
static Cups x = new Cups(); // (2)
// 第二次初始化静态变量Cups
static Cups y = new Cups(); // (2)
}
  来自CODE的代码片
  snippet_file_0.txt
  运行结果例如以下:
  Cup(1)
  Cup(2)
  Cups()
  Cups()
  Inside main()
  f(99)
  结论:这里面涉及到的知识非常多,有代码块、匿名内部类、static初始化等等,用这么一个大样例我感觉基本能说清楚了。
  须要提一下就是关于static变量、方法、代码块的初始化仅仅有一次,也就是当类第一次被调用的时候执行初始化。以后不管此类再被new多少次,均不再执行初始化。
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号