static关键字
非静态方法可以调用静态方法,反之则不行。
public class Student {
private static int age;//静态的变量 多线程
private double score;//非静态的变量
public void run(){
System.out.println("run");
go();
}
public static void go(){
System.out.println("go");
}
public static void main(String[] args) {
Student s1 = new Student();
//可以直接用类来调用,由于就是上面的类可以直接go()就能调用
Student.go();
//需要用对象来调用非静态的变量
s1.run();
System.out.println(Student.age);
System.out.println(s1.age);
System.out.println(s1.score);
}
}
静态代码块
public class Person {
//2.第二个输出,一般用来赋初始值
{
System.out.println("匿名代码块");
}
//1.第一个输出,只执行一次
static{
System.out.println("静态代码块");
}
//3.第三个输出
public Person() {
System.out.println("构造方法");
}
public static void main(String[] args) {
Person person1 = new Person();
System.out.println("===============================");
Person person2 = new Person();
}
}
静态导入包
//静态导入包
import static java.lang.Math.random;
import static java.lang.Math.PI;
public class Test {
public static void main(String[] args) {
System.out.println(random());
System.out.println(PI);
}
}