1.静态变量
静态变量被同类的所有对象共享。
public class test {
public static void main(String[] args) {
A a1 = new A();
A a2 = new A();
a1.temp++;
a2.temp++;
System.out.println(a1.temp);
System.out.println(a2.temp);
}
}class A{
public static int temp=0;
}
a1 a2都能访问temp。但不是同一个类无法访问。
原理图:
2.静态方法
在静态方法中可以访问静态变量及静态方法,不可访问普通属性和方法。
普通方法中可以访问静态变量及方法和普通属性及方法。
class A{
public static int temp=0;
public int ret=0;
public static void A1() {
temp = 1;
ret = 1;//错误
A2();
A3();//错误
}
public void A3(){
A1();A2();
temp=1;ret=1;
}
public static void A2(){
}
}
3.使用静态属性和方法并不需要实例化对象。stati修饰的属性和方法在加载类时就生成了(具体搜索大佬文章,还没学到)。
4.访问方法
对象名.静态变量名/方法名
类名.静态变量名/方法名
未学完,待补充。