静态变量
static 关键字可以用来修饰成员变量,该变量被称作静态变量,可以被所有的对象实例所共享。
public class student {
static String schoolName;
}
public class Example008{
public static void main(String[] args) {
student std1=new student();
student std2=new student();
student.schoolName="山东大学"; //类名.成员变量名用来访问
System.out.println(std1.schoolName);
System.out.println(std2.schoolName);
}
}
注意:
1、static只能用来修饰成员变量,而不能用来修饰局部变量。
2、类名.变量名
静态方法
public class Example008{
public static void main(String[] args) {
Student.say(); //调用静态方法1,此处不需要实例化对象就可以调用静态方法
Student st1=new Student();
st1.say(); //调用静态方法2
}
}
public class Student {
public static void say(){ //定义静态方法
System.out.println("Hello World");
};
}
静态方法的调用有两种: 类名.方法 或 实例对象名.方法
在静态方法中只能访问使用static修饰的成员,没有被static修饰的成员需要先创建对象才能访问。
静态代码块
public class Example008{
static { //定义静态代码块
System.out.println("执行了Example008类中的静态代码块");
};
public static void main(String[] args) {
Student std1=new Student();
System.out.println("##############################");
Student std2=new Student();
}
}
public class Student {
static { //定义静态代码块
System.out.println("执行了Student类中的静态代码块");
};
}
当类被加载的 时候,静态代码块会被执行。
由于类只能加载一次,因此静态代码块也只执行一次。所以我们可以看到Student std2=new Student();其实是没有被执行的。