static 可以修饰成员变量和方法,则为静态成员变量或静态方法,凡是static修饰的都表示只有一份,成员是属于类的,不属于类的某个实例,除了可以修饰变量和方法,还可以修饰代码块,static修饰的成员都可以使用类名.成员名直接访问
public static int i = 10;
静态变量表示该类的对象共享此变量,仅一份
public static void method(){}
静态代码块>构造方法>有参/无参构造
public class Person {
public static int m =10 ;
public int n ;
static {
System.out.println("我是静态代码块");
}
public Person(){
System.out.println("我是无参构造方法");
}
{
System.out.println("我是构造方法");
}
public static void main(String[] args){
Person person1 = new Person();
Person person2 = new Person();
System.out.println(Person.m);//10
System.out.println(person1.m+1);//11
System.out.println(person2.m);//11
}
}
原文:https://www.cnblogs.com/shifangxu/p/15221573.html