static
来源:互联网 发布:布料模拟 算法 编辑:程序博客网 时间:2024/05/21 15:58
在类中定义的数据成为类的数据成员,例如字段,常量等。而函数的成员方法则提供操作类的数据的功能,函数成员方法、属性、构造函数等。对象中的数据成员和方法一般都是对象私有的,即只有对象本身才能访问,其他对象不能直接对其操作。但是,如果在多个地方调用就需要产生多个实例。有些时候被调用的方法与实例的多少没有任何关系,该方法可能只是帮助方法。在这种情况下,不需要多个实例, 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 代码只执行了一次,构造函数执行了三次,也就是静态代码块会在加载的时候执行,而且只执行一次。
//static方法不能调用非static方法的原因:因为非static方法需要对象实例化。
- static
- static
- static{}
- static
- static
- Static
- static
- static
- Static
- static
- static
- static
- static
- static
- static
- static
- static
- static
- 发一个面试题,小测一下live wirter。
- mod函数 用法
- 数据库范式(1NF 2NF 3NF BCNF)详解一
- POJ 3311 Hie with the Pie -- TSP 状态压缩dp
- 发个地震数据的爬虫
- static
- 数据库范式(1NF 2NF 3NF BCNF)详解二
- Android中解析XML
- 2013-05-06 链接
- matlab-直方图小结
- 1.Model学习(Official Tutorials)
- POJ 2752 Seek the Name, Seek the Fame
- 打印包含n个括号的所有合法的组合
- 每天一个linux命令(43):killall命令