Day23static详解
static修饰德成员变量,属于类的本身,被该类德所有实例共享,在类中可以通过类名直接访问,再导入包时打破必须通过类名访问静态成员的规则,将指定的静态成员直接引入当前类的作用域
package oop1.Demo7;
//被fianl定义后就无法被其他类继承了
public final class Person {
//2 类用来赋值一些初始值
{
System.out.println("匿名代码块");
}
//1 只执行一次
static{
System.out.println("静态代码块");
}
//3
public Person(){
System.out.println("构造方法");
}
public static void main(String[] args) {
Person person = new Person();
System.out.println("=====================================");
Person person1 = new Person();//静态代码块不在被加载
}
//Person运行结果:
//静态代码块
//匿名代码块
//构造方法
//Person1运行结果
//匿名代码块
//构造方法
}
package oop1.Demo7;
import oop1.Demo6.Person;
//static
public class Student {
private static int age;//静态变量
private double score; //非静态变量
public void run(){
System.out.println("run");
}
public static void go(){
System.out.println("go");
}
public static void main(String[] args) {
Student s1 = new Student();
System.out.println(Student.age);
System.out.println(s1.score);
System.out.println(s1.age);
//若是一个变量需要在类中要反复用到,则推荐将其定义为静态变量
Student.go();//可以直接调用,甚至写成简化为go();也能调用成功
}
}
package oop1.Demo7;
//静态导入包
import static java.lang.Math.random;
import static java.lang.Math.PI;
public class Test {
public static void main(String[] args) {
System.out.println(Math.random());
//导入Math包之后
System.out.println(random());
System.out.println(PI);
}
}