1.静态变量和静态方法
//static:
public class Student {
private static int age;//静态的变量 多线程
private double score;//非静态的变量
public void run() {
}
public static void go() {
}
public static void main(String[] args) {
Student s = new Student();
System.out.println(s.age);
System.out.println(Student.age);
System.out.println(s.score);
//System.out.println(Student.score);//报错,非静态不能用类调用
//非静态方法可以直接访问静态方法
go();
//run();//报错
}
}
静态变量访问:类名.变量名;Student.age
对象名.变量名;s.age
非静态变量访问: 对象名.变量名;s.score
静态方法调用:同一个类中 方法名();
不同类中 类名.方法名();
非静态方法调用:先创建对象,对象名.方法名();
2.静态代码块
public class Demo04 {
// //代码块(匿名代码块) 创建对象时自动创建且在构造器之前
{
System.out.println("匿名代码块");
}
//1.静态代码块 类一加载立刻执行,且只执行一次
static {
System.out.println("静态代码块");
}
public Demo04() {
System.out.println("构造方法");
}
public static void main(String[] args) {
Demo04 d = new Demo04();
Demo04 d2 = new Demo04();
}
}
3.静态导入包
//静态导入包~
import static java.lang.Math.PI;
import static java.lang.Math.random;
public class Test {
public static void main(String[] args) {
//一般情况下生成随机数,Math.random();
System.out.println(random());
System.out.println(PI);
}
}
注:被final修饰的类不能再有子类!



