package com.oop.demo07;
//static
public class Student {
private static int age; //静态的变量
private double score; //非静态的变量
public void run(){
}
public static void go(){
new Student().run(); //需要单独调用,默认不加载 run()
}
public static void main(String[] args) {
Student.go(); //go() 有 static 修饰,和类一起加载可以直接调用
Student s1 = new Student();
System.out.println(Student.age);//使用当前类名直接调用对象
//System.out.println(Student.score); //无法引用,非静态的没有被加载
System.out.println(s1.age);
System.out.println(s1.score);
}
}
package com.oop.demo07;
public class Person {
//2:赋初始值
{
System.out.println("匿名代码块");
}
//1:静态代码块,只执行一次
static {
System.out.println("静态代码块");
}
//3
public Person() { //加上 void 后,没有单独调用不会输出
System.out.println("构造方法");
}
public static void main(String[] args) {
Person person1 = new Person();
System.out.println("===");
Person person2 = new Person();
}
}
输出结果:
静态代码块
匿名代码块
构造方法
===
匿名代码块
构造方法
package com.oop.demo07;
//静态导入包
import static java.lang.Math.random;
import static java.lang.Math.PI;
public class Test {
public static void main(String[] args) {
System.out.println(random());
System.out.println(PI);
}
}
常量final 不能使用父子继承