① static修饰属性:静态变量(类变量)
静态(加static) vs 非静态(不加static,实例变量)
public class Qer{
public static void main(String[] args){
Asd asd1 = new Asd();
asd1.age = 40;
asd1.name = "大哥";
Asd asd2 = new Asd();
asd2.age = 30;
asd2.name = “小哥”;
asd1.test = 10;
System.out.println(asd2.test);
//结果 不管是输出asd1.test还是asd2.test,结果都是10,尽管都没有asd2.test。static大家都可以用,而且都只能用同一个。
}
}
class Asd{
int age;
String name ;
static int test;
}
静态变量的加载要早于实例变量(非静态),还没有new实例的时候,静态变量已经存在了。
可以不new就可以调用了。如System.out.(类.static的变量。必须是静态的才可以用类来调用,否则就要造对象(new))
(随着类的加载而加载,只加载一次,存在方法区的静态域中)。
② static修饰方法(同上差不多)
加static的方法可以不new就调用方法(类.静态方法)
注:1.静态的方法:要是还需要调用方法和属性就只能调用静态的方法和属性,加static的方法和属性;
非静态的方法:不加static的随意调用
int a;
static int b;
public static void asd(){
zxc();//可以,是静态的
qwe();//不可以,不是静态的
a = 10;//不可以,不是静态的
b = 10;//可以,是静态的
}
public void qwe(){
}
public static void zxc(){
}
2.静态方法中不能使用this,super不能使用,这两个都是需要new出实例后才能用,静态的不需要new。