`
wxb880114
  • 浏览: 673839 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

浅析Static用法解析java语言

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

  public static void main(String[] args) {System.out.println(Math.random());}

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

  Static 不仅可以修饰方法还可以修饰属性,由于Static 修饰的方法或者属性与实例的多少没有任何的关系,可以理解为static 的方法和属性是可以在多个实例之间共享的。

  看以下实例:

  public class Text {static int count=0;public StaticCount(){count ++;}

  public static void main(String[] args) {StaticCount count1 = new StaticCount ();StaticCount count2 = new StaticCount ();System.out.println("count="+ count);}

  }

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

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

  public class Text{int count;static {System.out.println("in the static segment...");}

  public Text (){System.out.println("in the constuctor segment...");}

  public static void main(String[] args) {Text sd0 = new Text();}

  }

  运行结果:

  in the static segment...

  in the constuctor segment...

  大家注意到,通过static修饰的代码块在构造函数之前就执行了,实际上静态代码块是在程序加载(load)的时候执行的,而构造函数是在运行的时候执行的。静态代码块只加载一次,看以下实例:

  public class Text {static {System.out.println("in the static segment...");public Text (){System.out.println("in the constuctor segment...");}

  public static void main(String[] args) {Text sd0 = new Text ();Text sd1 = new Text ();Text sd2 = new Text ();}

  }

  运行结果:

  in the static segment...

  in the constuctor segment...

  in the constuctor segment...

  in the constuctor segment...

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

原文出自【比特网】,转载请保留原文链接:http://soft.chinabyte.com/database/334/12131334.shtml
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics