5.12 static关键字
1、静态属性和方法
package com.jessie.oop.Demo07;
// 类中,修饰成员变量;方法,修饰成员方法。静态方法或静态属性。
public class Student {
// 1、静态、非静态属性的理解
private static int age; // 静态属性。可用多种调用方法,建议直接使用类名调用。能被类中的所有实例共享,在多线程中用
private String name; // 非静态变量。只能通过对象调用
private double score; // 非静态变量
public static void main(String[] args) {
// 1、属性的理解
Student s1 = new Student();
System.out.println(s1.score); // 非静态变量。只能通过对象调用
System.out.println(Student.age); // 静态变量
// 2、方法的理解
go(); // 非静态方法直接调用
Student s2 = new Student();
s2.run(); //非静态方法,过对象调用
}
// 2、静态、非静态方法的理解
public void run(){
}
public static void go(){
}
}
2、 静态代码块
public class Person {
// 静态代码块 》 匿名 》 构造器
// 2、匿名代码块。可用于赋初始值
{
System.out.println("匿名代码块");
}
// 1、静态代码块。 只在第一次调用该类时一起加载
static {
System.out.println("静态代码块");
}
// 3、构造方法
public Person(){
System.out.println("构造器");
}
public static void main(String[] args) {
Person p1 = new Person(); // 测试代码块的运行顺序
System.out.println("===================");
Person p2 = new Person();
}
}

3、静态导入包
// 5.12.3 静态导入包。
import static java.lang.Math.random
import static java.lang.Math.PI
public class Test {
public static void test(String[] args) {
System.out.println(random());
System.out.println(PI);
}
}

浙公网安备 33010602011771号