日期:2014-05-20  浏览次数:20592 次

菜鸟求教:这种static写法是什么意思
class   A
{
      ......
      static   final   void   add(String   entity,   int   value)  
      {
          .......
      }
      ......
      static
      {
            add( "&nbsp ",160)
      }
}


请问:(1)第二个static这样写是什么意思?
            (2)在html实体字符里 "&nbsp "与160之间是什么关系?

------解决方案--------------------
你没有把add的方法体内的东西写出来,回答不了你 "&nbsp "与160之间有什么关系;
只知道 "&nbsp "在html中是空格。。。
第二个static的用噶也没有看过。。。是内部类?不清楚。。。等高手。。。
------解决方案--------------------
第二个static是静态块,类加载(不管是不是需要实例化)的时候会先调用到。
------解决方案--------------------
static块内的代码只在JVM第一次加载该类的时候运行
首先调用的是static静态快的代码,然后调用启动方法.而static块的执行顺序是由代码的编写顺序执行的过程.

------解决方案--------------------
static
{
add( "&nbsp ",160)
}
被成为静态块 它在类加载的时候就会执行 通过它调用add方法 执行方法里的语句
------解决方案--------------------
哦,又学到一点了
------解决方案--------------------
匿名内部类,不知道是不是
------解决方案--------------------
第二个static是静态代码块
------解决方案--------------------
静态块里的代码不一定是第一次被加载时执行,
确切的说应该是第一次实例化的时候执行~
因为他的执行和类的加载方式有关:
看看下面的:
1,测试类:
package com.daniel.test;

public class TestStatic {
static{
System.out.println( "执行静态块! ");
}
public void print(){
System.out.println( "执行TestStatic.print()! ");
}
}
2,主类:
package com.daniel.test;
public class StaticTest {
public static void main(String[] args) throws Exception {
StaticTest st = new StaticTest();
System.out.println( "准备加载com.daniel.test.TestStatic... ");
Class clazz = st.getClass().getClassLoader().loadClass( "com.daniel.test.TestStatic ");
System.out.println( "加载com.daniel.test.TestStatic成功! ");
System.out.println( "准备实例化com.daniel.test.TestStatic... ");
TestStatic ts = (TestStatic)clazz.newInstance();
System.out.println( "实例化com.daniel.test.TestStatic成功! ");
ts.print();
}
}

3,执行结果:
准备加载com.daniel.test.TestStatic...
加载com.daniel.test.TestStatic成功!
准备实例化com.daniel.test.TestStatic...
执行静态块!
实例化com.daniel.test.TestStatic成功!
执行TestStatic.print()!


从结果很明显看出,静态块的执行是类第一次实例化的时候进行的~~~~~
而 不是 大家常说的第一次加载类的时候执行的!!!!!
------解决方案--------------------
楼上的都说的很清楚了!
顶下!