static关键字详解
- static静态变量或方法可直接被类使用,如Student.age = 10;
- 非静态变量或方法在使用时需要new一个对象,通过对象进行调用
- 在static静态方法中不能调用非静态方法,因为static静态方法是和类一起加载的,此时非静态方法还未加载出来,编译器认为其不存在
- 在非静态方法中可以调用static静态方法
- static静态代码块只执行一次
- 执行顺序:静态代码块>匿名代码块>无参构造器
- 静态导入某个工具类中的某个方法,详情见下面代码
- 例:import static java.lang.Math.random;
代码示例:
package oop.Demo06;
public class Student {
//static静态变量可以被类直接使用
//非静态变量需要new一个对象
private static int age = 10; //静态
private double score = 100; //非静态
//静态方法和属性是和类一起加载的,如果在静态方法中使用非静态方法将会报错,因为此时非静态方法还未加载,不存在
public static void run(){
//go(); 报错
}
public void go(){
run();
}
public static void main(String[] args) {
Student student = new Student();
student.age = 1;
student.score = 90;
System.out.println(student.age); //1
System.out.println(student.score); //90
System.out.println(Student.age); //1
//System.out.println(Student.score); 报错
student.go();
student.run();
//Student.go(); 报错
Student.run();
}
}
package oop.Demo06;
import static java.lang.Math.random;
public class Test {
public static void main(String[] args) {
System.out.println(random()); //输出随机数
//若想要在上述语句中只写random();则静态导入 import static java.lang.Math.random;
}
}
package oop.Demo06;
public class Person {
//第三个
public Person() {
System.out.println("无参构造器");
}
//第二个 可用来赋初值
{
System.out.println("匿名代码块");
}
//第一个 static只执行一次
static {
System.out.println("静态代码块");
}
public static void main(String[] args) {
Person person = new Person(); //静态代码块,匿名代码块,无参构造器
System.out.println("==================");
Person person1 = new Person(); //匿名代码块,无参构造器
}
}