Core Java (七) Java中的static修饰符

static为静态的意思,常用来修饰内部类,方法,变量。


静态域

static修饰的变量在每个类中只有一个副本,即这个类的所有对象共享一个变量,它属于类,不属于任何独立的对象。

package com.xujin;

class Base{
	protected static int MAX = 100;
}

public class Another extends Base{
	public static void main(String[] args){
		Base base1 = new Base();
		Base base2 = new Base();
		Base base3 = new Base();
		System.out.println(base1.MAX);//100
		System.out.println(base2.MAX);//100
		System.out.println(base3.MAX);//100
		base1.MAX = 10;
		System.out.println(base1.MAX);//10
		System.out.println(base2.MAX);//10
		System.out.println(base3.MAX);//10
	}
}


静态常量

static final 修饰符,即为常量。

public class Math{
		...
		public static final PI = 3.14159265358979323846;
		...
	}

Math.PI就可以访问该常量。

public static final 修饰符很重要,他可以公开给别的类但不允许其他类修改。



静态方法

static方法是静态方法,是一种不能向对象实施操作的方法(即没有隐式的参数this),比如Math.random(),Math.pow(x, a);  

不能在一个static方法内部访问非static变量,可以通过类名(推荐)和对象名(不推荐)调用这个方法。

静态方法不能被重写,一个非static(普通的)方法也不能在子类中重写为static 方法。另外,一个static方法也不能在子类中重写为static 方法中,因为重写必须符合多态性,而static并不符合这个规定。

如下例子:

package com.xujin;

class Base{
	public static void aMethod(){
		System.out.println("Base a");
	}
	public void bMethod(){
		System.out.println("Base b");
	}
}

public class Another extends Base{
	public static void main(String argv[]){
		Base so = new Another();
		Another fo = new Another();
		
		so.aMethod();//Base a		
		fo.aMethod();//Another a
		
		so.bMethod();//Another b
		fo.bMethod();//Another b
		
	}
	public static void aMethod(){
		System.out.println("Another a");
	}	
	public void bMethod(){
		System.out.println("Another b");
	}	
}

其中有一个静态方法aMethod()和一个非静态方法bMethod(),bMethod()符合多态性,而静态方法aMethod()不符合多态性。

所以说这个不属于方法重写。



main方法

当启动程序的时候还没有任何一个对象,所以静态的main方法将执行并创建程序所需要的对象。

main方法也可以用来对某个类进行单元测试。



静态内部类

把一个类隐藏在另一个类的内部,内部类不可引用外部类对象,取消了产生的引用。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值