在类中定义的数据成为类的数据成员,例如字段,常量等。而函数的成员方法则提供操作类的数据的功能,函数成员方法、属性、构造函数等。对象中的数据成员和方法一般都是对象私有的,即只有对象本身才能访问,其他对象不能直接对其操作。但是,如果在多个地方调用就需要产生多个实例。有些时候被调用的方法与实例的多少没有任何关系,该方法可能只是帮助方法。在这种情况下,不需要多个实例, java 引入了static,先看一个实例:

  1. public static void main(String[] args) {  
  2.           
  3.         System.out.println(Math.random());  
  4.  
  5.     }  

 在jdk中Math的random方法的作用是提供一个产生随机数的功能,它只是一个帮助方法,与Math中的实例变量没有任何关系,所以不需要调用一次产生一个实例,只通过类直接调用就可以了,在此JDK中就提供了random这static(静态)方法。

Static 不仅可以修饰方法还可以修饰属性,由于Static 修饰的方法或者属性与实例的多少没有任何的关系,可以理解为static 的方法和属性是可以在多个实例之间共享的。
看以下实例:
  1. public class Text {  
  2.     static int count=0;  
  3.     public StaticCount(){         
  4.         count ++;  
  5.     }  
  6.     public static void main(String[] args) {  
  7.         StaticCount count1 = new StaticCount ();  
  8.         StaticCount count2 = new StaticCount ();  
  9.         System.out.println("count="+ count);
  10.     }  

运行结果:count=2

从以上实例可以看出,count1所指向的对象和 count2指向的对象共享了static变量。实际上我们经常提到的入口函数也是个static静态方法,静态方法与实例没有任何的关系,它可以直接调用静态变量。 也可以通过实例的引用调用静态属性或者方法,效果是相同,只是不需要而已。

可以把某段代码直接通过static修饰,看以下实例:

  1. public class Text{  
  2.     int count;  
  3.     static {  
  4.         System.out.println("in the static segment...");  
  5.     }  
  6.     public Text (){  
  7.         System.out.println("in the constuctor segment...");  
  8.     }  
  9.     public static void main(String[] args) {  
  10.         Text sd0 = new Text();  
  11.     }  
  12. }  

运行结果:

in the static segment...
in the constuctor segment...
 
大家注意到,通过static修饰的代码块在构造函数之前就执行了,实际上静态代码块是在程序加载(load)的时候执行的,而构造函数是在运行的时候执行的。静态代码块只加载一次,看以下实例:
  1. public class Text {  
  2.     static {  
  3.         System.out.println("in the static segment...");  
  4.     public Text (){  
  5.           
  6.         System.out.println("in the constuctor segment...");  
  7.     }   
  8.     public static void main(String[] args) {  
  9.         Text sd0 = new Text ();  
  10.         Text sd1 = new Text ();  
  11.         Text sd2 = new Text ();  
  12.     }  
  13. }  

 

运行结果:
in the static segment...
in the constuctor segment...
in the constuctor segment...
in the constuctor segment...
从运行结果可以看出static 代码只执行了一次,构造函数执行了三次,也就是静态代码块会
在加载的时候执行,而且只执行一次。