1. 静态变量也叫类变量,实例变量也叫非静态变量,静态变量是所有对象共享的,非静态变量每个对象有自己的一份拷贝。
class TestStatic{
public int a;
public static int b;
}
public static void main(String[] args) {
TestStatic ts = new TestStatic();
ts.a = 100;
ts.b = 200;
TestStatic ts2 = new TestStatic();
ts2.a = 300;
ts2.b = 400;
System.out.println("ts a:"+ts.a);
System.out.println("ts b:"+ts.b);
System.out.println("ts2 a:"+ts2.a);
System.out.println("ts2 b:"+ts2.b);
}
/* 输出结果
* ts a: 100
* ts b: 400
* ts2 a: 300
* ts2 b: 400
*/
2. 静态变量通过类名称可以直接访问
class TestStatic{
public int a;
public static int b;
}
public static void main(String[] args) {
TestStatic ts = new TestStatic();
ts.a = 100;
TestStatic.b = 200;
System.out.println("ts a:"+ts.a);
System.out.println("ts b:"+TestStatic.b);
}
3. 静态方法可以直接通过类名称来访问,静态方法不能访问非静态方法或者变量,反之可以
class TestStatic{
public int a;
public static int b;
private static int z;
public void m2(){
System.out.println("非静态方法,也叫实例方法..");
TestStatic.m1(); //非静态方法可以访问静态方法
TestStatic.b = 300; //非静态方法可以访问静态变量
}
public static void m1(){
// a = 100; // 静态方法不可以访问非静态变量
// m2(); // 静态方法不可以访问非静态方法
System.out.println("静态方法m1");
}
}
4. 静态代码块,有时为了提高效率,会使用静态代码块,将静态变量括起来,静态代码块中不能写静态方法,只能加静态变量。
public class Test {
static{
int c = 1;
int d = 2;
System.out.println("static 2");
}
static{
int x = 100;
int y = 200;
// 不能写方法
//void m1(){
//
//}
System.out.println("static 1");
}
}
/*
* 静态代码块的加载顺序从上向下
* 上面类的打印结果如下:
* static 2
* static 1
*/