您的位置:首页 > 编程语言 > Java开发

java static 变量与方法

2015-10-20 10:52 369 查看
最近在看马士兵的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方法时,不会将引用传过来,因此无法访问非静态变量。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java static