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方法也可以用来对某个类进行单元测试。
静态内部类
把一个类隐藏在另一个类的内部,内部类不可引用外部类对象,取消了产生的引用。