使用:
1.类成员变量
2.类方法
1.类方法中不能有非静态成员。 因 为非静态成员与实例相关,通过对象间接使用。
2.不能使用this。
3.static块:和数据成员时并列的位置,用于类初始化类装入时执行一次(第一次创建对象,第一次使用static成员,不同的静态块,按在类中的顺序执行)
加上关键字static(静态的)就能创建这样的成员。如果一个成员被声明为static,它就能够在它的类的任何对象创建之前被访问,而不必引用任何对象。你可以将方法和变量都声明为static。static 成员的最常见的例子是 main( ) 。因为在程序开始执行时必须调用main() ,所以它被声明为static。
下面的例子显示的类有一个static方法,一些static变量,以及一个static 初始化块:
// Demonstrate static variables,methods,and blocks. class UseStatic { static int a = 3; static int b; static void meth(int x) { System.out.println("x = " + x); System.out.println("a = " + a); System.out.println("b = " + b); } static { System.out.println("Static block initialized."); b = a * 4; } public static void main(String args[]) { meth(42); } }
一旦UseStatic 类被装载,所有的static语句被运行。首先,a被设置为3,接着static 块执行(打印一条消息),最后,b被初始化为a*4
或12。然后调用main(),main() 调用meth() ,把值42传递给x。3个println ( ) 语句引用两个static变量a和b,以及局部变量x
。
注意:在一个static 方法中引用任何实例变量都是非法的。
下面是该程序的输出:
Static block
initialized.
x = 42
a = 3
b = 12
下面是一个例子。在main() 中,static方法callme() 和static 变量b在它们的类之外被访问。
class StaticDemo { static int a = 42; static int b = 99; static void callme() { System.out.println("a = " + a); } } class StaticByName { public static void main(String args[]) { StaticDemo.callme(); System.out.println("b = " + StaticDemo.b); } }
原文:http://www.cnblogs.com/wsylly/p/3573227.html