目录
1. 概念
2. 静态属性
3. 静态方法
4. 静态块
5. 加载顺序
1. 概念
/**
* 概念
* 1、凡是静态的,先于对象存在的,与对象无关的
* 2、凡是静态的,就是共享的
*
* @author zhongaidong
*/
public class StaticDemo01 {
public static void main(String[] args) {
// 成员变量必须存在对象
Fruit f1 = new Fruit();
f1.n = 20;
System.out.println(f1.num); // f1.num 自动转换成Fruit.num
// 类属性、静态属性
Fruit.num = 200;
System.out.println(f1.num); // f1.num 自动转换成Fruit.num
// System.out.println(Fruit.num);
System.out.println(f1);
// 改变静态属性
// f1.num =1000;
Fruit.num = 1000;
Fruit f2 = new Fruit();
System.out.println(f2);
}
}
class Fruit {
// 成员属性
public int n;
// 类属性、静态属性
public static int num;
public void test(int num) {
// System.out.println(Fruit.num);
System.out.println(num);
}
// 构造器
// 成员方法
}
2. 静态属性
/**
* 静态属性
* static +属性: 静态属性 ,类属性 -->可以用于计数 、自动编号
*
* 注意:
* 1. 为了增强可读性,避免混淆成员变量与类变量,一致推荐使用 类.静态属性,
* 不要使用 对象.静态属性 来调用类属性
* 2. 当前类中, 类. 可以省略 ,如果 形参|局部变量 与静态变量同名,不要省略
*
* @author zhongaidong
*/
public class StaticDemo02 {
public static void main(String[] args) {
new Fruit2();
new Fruit2();
new Fruit2();
System.out.println(Fruit2.num);
Fruit2 f1 = new Fruit2();
System.out.println(f1.no);
}
}
class Fruit2 {
String no;
// 类属性、静态属性
public static int num; // 共享
Fruit2() {
num++;
no = "zad" + num;
}
// 构造器
// 成员方法
}
3. 静态方法
/**
* 静态方法:static + 方法
* 1. 静态方法 只能访问静态属性|信息,不能访问成员信息
* 2. 成员方法:可以访问一切
* 3. 静态方法不能访问this,super
* 4. 不能使用 new 类.静态方法() 来调用静态方法。
*
* @author zhongaidong
*/
public class StaticDemo03 {
public static void main(String[] args) {
Fruit3.test();
// 静态方法 Math.random();
// new Math().random(); // 不能使用 对象|成员.访问
}
}
class Fruit3 {
String no;
// 类属性、静态属性
public static int num; // 共享
Fruit3() {
}
// 构造器
// 成员方法
// 静态方法
public static void test() {
// System.out.println(this); //this也是对象信息
num = 10;
// no =2; //成员信息
new Fruit3().no = "2";
}
}
4. 静态块
/**
* 静态块:static + 块{}
* 1. 位置:类中方法外
* 2. 作用:加载类信息,且只加载一次。
* 3. 优化:JUST IN TIME : 及时性。使用才加载,如果仅声明变量,不会加载。
*
* @author zhongaidong
*/
public class StaticDemo04 {
public static void main(String[] args) {
Fruit f1 = null; // 如果仅声明变量,不会加载。
System.out.println(f1);
f1.num = 100; // JUST IN TIME,使用即加载
System.out.println(f1.num);
// new Fruit(); // 使用即加载
// new Fruit(); // 且只加载一次。
}
}
class Fruit4 {
String no;
// 类属性、静态属性
public static int num; // 共享
static {
// 静态块 :加载类信息
num = 1000;
System.out.println("....加载类信息");
}
}
5. 加载顺序
/**
* 加载顺序
* 先声明变量,再一次加载。
*
* @author zhongaidong
*/
public class StaticDemo05 {
public static void main(String[] args) {
System.out.println(Fruit5.num);
}
}
class Fruit5 {
//
// 1、public static Fruit f1 =new Fruit() ;
public static int num = 20; // 共享
public static Fruit5 f1 = new Fruit5();
// 2、public static Fruit f1 =new Fruit() ;
Fruit5() {
num = 30;
}
}