java中static关键字的说明

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

以上是个人实践的理解,有不足之处请留言。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值