static
静态 与 非静态
变量
静态变量相对于类来说只有一个,类中所有实例共享
public class Student {
private static int age; //静态变量
private double score; //非静态变量
public static void main(String[] args) {
Student s1 = new Student();
System.out.println(Student.age); //通过类来调用,叫类变量
//System.out.println(Student.score); //无法通过类变量调用非静态变量
System.out.println(s1.age); //通过对象来调用
System.out.println(s1.score); //通过对象来调用
}
}
方法
非静态方法不可以直接调用
public class Student {
public void run(){}
public static void main(String[] args) {
//run();因为是非静态方法,所以需要先 new 出对象
}
}
需要先new出对象
public class Student {
public void run(){}
public static void main(String[] args) {
//run();因为是非静态方法,所以需要先 new 出对象
new Student().run(); //new 出 Student 之后才可以调用 run()
}
}
静态方法可以直接调用
public class Student {
public static void go(){}
public static void main(String[] args) {
go();
}
}
但是非静态方法可以直接访问静态方法
public class Student {
public static void go(){}
public void run(){
go();
}
public static void main(String[] args) {
new Student().run();
go();
}
}
静态方法无法调用非静态方法。静态方法和类一起加载,加载的时候非静态方法还未加载,所以静态方法无法调用非静态方法。
代码块
public class Person {
{
//代码块(匿名代码块) //生成在构造器之前
}
static {
//静态代码块 //和类一起加载
}
}
public class Person {
{
System.out.println("匿名代码块");
}
static {
System.out.println("静态代码块");
}
public Person(){
System.out.println("构造方法");
}
public static void main(String[] args) {
Person person = new Person();
}
}
会获得输出
静态代码块
匿名代码块
构造方法
静态代码块最早和类一起加载,其次是匿名代码块,最后是构造方法
静态代码块只执行一次
public class Person {
{
System.out.println("匿名代码块");
}
static {
System.out.println("静态代码块");
}
public Person(){
System.out.println("构造方法");
}
public static void main(String[] args) {
Person person = new Person();
System.out.println("====================");
Person person2 = new Person();
}
}
会获得输出
静态代码块
匿名代码块
构造方法
====================
匿名代码块
构造方法
因为静态代码块只执行一次,所以第二次不会获得静态代码块的输出
静态导入包
//静态导入包
import static java.lang.Math.random; //导入 random 方法
public class Test {
public static void main(String[] args) {
System.out.println(random()); //获取一个随机数
}
}
其他
被 final 修饰的类无法被继承