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

java中static关键字的说明

2016-06-03 14:24 561 查看
1、一旦用static关键字修饰,那么在其成员方法中不能用本类的this关键字,即不能用本类中非静态成员。

public  class H{
int a=1;

public static void main(String[] args){
System.out.println(""+a);
h();
}

public void h(){
System.out.println("h");
}
}
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">以上代码会编译报错:</span>
--无法从静态上下文中引用非静态 变量 a

--无法从静态上下文中引用非静态 方法 h()

2、用static关键字修饰后的成员,在new对象前就已存在并可调用,调用方法为:类名.成员名。

public  class H{
static int a=1;
public static void main(String[] args){
System.out.println(H.a+"");
h();
}

public static void h(){
System.out.println("h");
}
}

输出:

1

h

3.成员被static关键字修饰后,该类所有对象共用这一份成员。

public  class H{
static int a=1;
public static void main(String[] args){
H h1=new H();
H h2=new H();
System.out.println("h1.a="+h1.a);
System.out.println("h2.a="+h2.a);
h1.a=2;
System.out.println("h2.a="+h2.a);
h2.a=3;
System.out.println("h1.a="+h1.a);
}
}
输出:

h1.a=1

h2.a=1

h2.a=2

h1.a=3

以上是个人实践的理解,有不足之处请留言。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: