static关键字可以修饰属性、方法、游离块、内部类。分别称为静态属性、静态方法、静态游离块和内部类。
没有static修饰的属性,对象和对象之间的属性是不共享的。 类中的属性和方法都是对 对象的描述 ,而有些属性和 方法是修饰类的,例如人类的人口数量、人类的起源、人类的文明 ,这些属性和方法就可以用static修饰。
确切的理解:static修饰的属性,对象和对象之间是共享的。
public class Person {
String name;
//人口总数 显示内存中的人口总数
static int count ;
public Person() {
count++;
}
}
public static void main(String[] args) {
Person p1 = new Person();
Person p2 = new Person();
//count属性,对象和对象之间是可以共享的
System.out.println(p1.count);
System.out.println(p2.count);
}
由于静态的属性和方法不是修饰对象的,而是修饰类的,因此调用静态的属性和方法可以使用类名调用
public static void main(String[] args) {
Person p1 = new Person();
Person p2 = new Person();
//类名为Person,用类名调用
System.out.println(Person.count);
}
//静态方法
public static void civilization() {
System.out.println("人类的文明发展");
}
public static void main(String[] args) {
Person p1 = new Person();
Person p2 = new Person();
System.out.println(Person.count);
Person.civilization();
}
静态方法中不能使用this关键字,不能调用非静态的属性和方法
static和private修饰的方法不能被重写
public static void main(String[] args) {
Person.method();
Animal.method();
Person p = new Person();
p.method();
Animal a = new Person();
//静态方法和对象无关的 ,和类相关
//a是Animal类型 , a.method() 是Animal.method();
a.method();
}
游离块
又叫初始化块、构造块, 可以写在类中
当调用构造器时,执行游离块,先执行游离块,再执行构造器代码,当发现每个构造器都要执行一段代码,写在游 离块中
游离块的执行顺序:先父类游离块、父类构造器、子类游离块、子类构造器
静态游离块
在游离块的前面加 static修饰 ,静态游离块在类被加载时执行,静态游离块只执行一次
静态游离块、游离块、构造器的执行顺序:父类静态游离块、子类静态游离块、父类游离块、父类构造器、子类游 离块、子类构造器
public class Test {
static {
System.out.println("执行静态游离块");
}
String name;
public void method() {
}
public static void method2() {
}
public static void main(String[] aa) {
//仅仅是声明,不加载Test类
//JVM 执行了 Test.main()
//加载了Test类
//Test t ;
//method(); //错误 可以是 Test t = new Test() ; t.method(); //正确
method2();
}
}
例:
/*Person 类*/
public class Person {
static {
System.out.println("Person的静态块");
}
{
System.out.println("Person类的匿名块");
}
public Person() {
System.out.println("Person的构造方法");
}
}
/*Student 类*/
public class Student extends Person {
static{
System.out.println("Student 静态块");
}
{
System.out.println("Student匿名块");
}
public Student() {
System.out.println("Student的构造方法");
}
}
/* 测试类*/
public class Test {
public static void main(String[] args) {
new Student();
}
}
执行结果 :