Static关键字
public class Student {
private static int age; //静态的变量
private double score;//非静态的变量
public void run(){
go(); // 非静态方法可以调用静态方法,不可以调用非静态方法
}
public static void go(){
go(); // 静态方法可以调用静态方法,不可以调用非静态方法
}
public static void main(String[] args) {
// Student s1 = new Student();
// System.out.println(s1.score);
// System.out.println(s1.age);
// System.out.println(Student.age);
// // System.out.println(Student.score); 类名.属性 只能访问静态的变量
// 非静态方法无法通过类名直接调用 Student.run;
Student s2 = new Student();
s2.run();
// 静态方法可以直接通过类名调用
Student.go();
}
}
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 p1 = new Person();
System.out.println("=======================");
Person p2 = 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);
}
}