直接在代码展示,方便阅读理解~
一.对变量及方法
//static
public class Student {
private static int age; //静态变量 多线程使用
private double score; //非静态变量
public void run(){
go(); //非静态方法可以调用静态方法
}
public static void go(){
}
public static void main(String[] args) {
Student s1 = new Student();
System.out.println(Student.age); //只有静态变量,才能用类名进行调用
System.out.println(s1.score);
System.out.println(s1.age);
go(); //静态方法可以调用静态方法,不能调用非静态方法
}
}
二.对代码块
public class Person {
{
System.out.println("代码块(匿名代码块)"); //第二个执行,可以用来赋初始值
}
static {
System.out.println("静态代码块"); //最先执行,且只执行一次
}
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(Math.random()); 使用静态导入包后,可以省略Math 下同
System.out.println(random());
System.out.println(PI);
}
}