视频学习地址
前言
static可以理解为静态的修饰符
案例1:
public class Student{
private double score; //非静态变量
private static int age; //静态变量
public void go(){ //非静态方法
System.out.println("go");
}
public static void run(){ //静态方法
System.out.println("run");
}
public static void main(String[] args) {
//private在自己的类中是可以直接调用的,无需用到get/set
//调用变量属性
Student s1 = new Student();
System.out.println(s1.age); //调用的实例化变量
System.out.println(s1.score); //调用的实例化变量
System.out.println(Student.age); //调用的静态变量
//System.out.println(Student.score); 因为score是非静态变量,故无法调用,此处报错
//调用方法
Student s2 = new Student();
s2.go(); //调用的实例化方法
Student.run(); //调用的静态方法 可以直接写run();
}
}
案例2:
public class Person {
{
//代码块(匿名代码块)
System.out.println("匿名代码块");
}
static {
//静态代码块(一般用来初始化一些数值)
//和类一起加载,只执行一次
System.out.println("静态代码块");
}
public Person() {
System.out.println("构造方法");
}
public static void main(String[] args) {
Person p1 = new Person();
System.out.println("----------------");
Person p2 = new Person();
}
//输出结果:
//静态代码块
//匿名代码块
//构造方法
//----------------
//匿名代码块
//构造方法
}
案例3:
import static java.lang.Math.random; //静态导入包
public class Application {
public static void main(String[] args) {
System.out.println(Math.random()); //产生随机数
System.out.println(random()); //可以直接写random()
}
}