java static 变量与方法

来源:互联网 发布:广州数控gsk980tdc编程 编辑:程序博客网 时间:2024/05/16 01:16
最近在看马士兵的java视频,看到static用法。总结如下:
static变量为静态变量,为类的公用变量,非静态和静态方法均可访问,可直接用类名+ . 调用。内存中存放data区域,仅有一份值。

static方法为静态方法,可直接类名+ . 也可以直接使用(比如main)。调用static方法时不会将对象的引用传给他,因此static方法不可访问非static变量。


public class ThisStaticDemo{String name;    static int age;static int sid=100;    public ThisStaticDemo (){         this.age=21;sid++;    }         public ThisStaticDemo(String name,int age){this();        this.name="Mick";    }     static void p(){System.out.println("我是静态方法");}private void print(){p();System.out.println(ThisStaticDemo.sid);        System.out.println("最终名字="+this.name);        System.out.println("最终的年龄="+this.age);    }    public static void main(String[] args) {p();System.out.println(ThisStaticDemo.sid);ThisStaticDemo tt=new ThisStaticDemo("",0); tt.print();    }}

1、静态方法 p() 可在非静态方法print()和静态方法main()直接使用,无需创建对象引用。
2、静态变量 sid 可在非静态方法print()和静态方法main()直接调用,无需创建兑现给引用。

如果在将print()设置为静态方法,代码如下;

public class ThisStaticDemo{String name;    static int age;static int sid=100;    public ThisStaticDemo (){         this.age=21;sid++;    }         public ThisStaticDemo(String name,int age){this();        this.name="Mick";    }     static void p(){System.out.println("我是静态方法");}private static void print(){p();System.out.println(ThisStaticDemo.sid);        System.out.println("最终名字="+this.name);        System.out.println("最终的年龄="+this.age);    }    public static void main(String[] args) {p();System.out.println(ThisStaticDemo.sid);ThisStaticDemo tt=new ThisStaticDemo("",0); tt.print();    }}

编译有以下错误:
java:21: 错误: 无法从静态上下文中引用非静态 变量 this
        System.out.println("最终名字="+this.name);
                                   ^
java:22: 错误: 无法从静态上下文中引用非静态 变量 this
        System.out.println("最终的年龄="+this.age);
                                    ^
2 个错误

-----------------

由于在代用static方法时,不会将引用传过来,因此无法访问非静态变量。

0 0