Java中的关键字 static

 
public class HelloWord{
    public static void main(String[]a){
        System.out.printIn("Hello World");
    }
}
//静态变量,即类的共有成员,只依赖于类存在,不需要对象实例。
//所有对象实例中的静态变量的值 都共享存储在一个共同的栈空间
public class staticTest {
    static int num = 5;
    int num1=5;
    public staticTest(int num,int num1){
        this.num=num ;
        this.num1=num1;
    }
    public static void main(String[]a){
        System.out.println(staticTest.num);//可以直接通过类来进行访问
     // System.out.println(staticTest.num1);//这句是错误的
        System.out.println("**********华丽丽的分界线**************");
        staticTest obj=new staticTest(10,10);
        System.out.println(obj.num);
        System.out.println(staticTest.num);
      //证明了指向是同一块的内存空间 } }
//静态方法也不需要通过对象的引用,可以直接通过类名引用
//静态方法不能使用非静态变量,不能引用非静态方法
public class staticTest {
    static int a = 1;
    int b = 2;
    public static void f1()
    {
        System.out.println("wwwww");
        System.out.println(a);
        //System.out.println(b);  //不能用非静态的
        //f2()                    //error, cannot call non-static method
    }
    public void f2()
    {
        System.out.println("23333");
        f1();
        System.out.println(a);
        System.out.println(b);   //非静态函数调用非静态变量
    }
    public static void main(String[] a)
    {
        staticTest.f1();
        //staticTest.f2(); //error, 不能使用类名来引用非静态方法
    }
}
//static块   就是有static的代码块。

在程序运行期间,只运行一次(第一次加载的时候调用)
执行顺序:static代码块>匿名块>构造函数


 

猜你喜欢

转载自www.cnblogs.com/yoriko/p/12336944.html