这是学习static 时的点点经验,供分享。
1.static 方法介绍
使用static限定的方法称为 静态方法 或 类方法 。与非static方法的区别是:非static方法的调用必须通过创建该类的对象调用。Static方法则不需要,直接使用 类名.静态方法名 调用即可 。
2.static 属性介绍
static 属性又称之为 类属性 , 可以不创建类的对象而直接调用 ;另外一个特征就是,类的某一个对象的static属性值被改变后,这个类所有对象的static属性值都会被改变 。下面是测试的实例:
/**
* static 测试,静态方法(类方法)与静态属性(类属性)
* @author Jellen
*
*/
public class TestStatic {
private static int count = 0;
public static void main(String [] args){
System.out.println("--this is a main method!");
TestStatic.staticMethod(); //通过类名直接访问静态方法(类名.静态方法)
//TestStatic.noStaticMethod(); //errors
TestStatic ts = new TestStatic(); //调用非静态方法时,就必须先创建对象,通过对象调用
ts.noStaticMethod();
TestStatic.count = 100;
System.out.println("\n--this is a class's static count: " + count); //静态属性的值
TestStatic value = new TestStatic();
value.count = 50;
System.out.println("--this is a object's static count: " + ts.count);
System.out.println("--object reference after count: " + count);//当static 属性值改变之后,所有该属性值都会改变
}
public static void staticMethod(){
System.out.println("\n--this is a static method!");
}
public void noStaticMethod(){
System.out.println("\n--this isn't a static method!");
}
}
------output---------------------------------
--this is a main method!
--this is a static method!
--this isn't a static method!
--this is a class's static count: 100
--this is a object's static count: 50
--object reference after count: 50