Java基础:static静态
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 go(){}//静态方法
public static void main(String[] args) {
new Student().go();//通过对象调用
Student.go();//通过类调用
go();//当前类中可以直接调用
//run();//非静态不能直接调用
}
}
代码块
-
匿名代码块:创建对象时自动创建,不能主动调用对象
-
静态代码块:加载就执行,只执行一次
-
调用顺序:静态代码块->匿名代码块->构造方法
//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) {
//调用Math.random()方法可以通过静态导入包替代
System.out.println(Math.random());
System.out.println(random());
System.out.println(PI);
}
}

浙公网安备 33010602011771号