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 s1 = new Student(); System.out.println(Student.age); //System.out.println(Student.score);//score非静态不能调用 System.out.println(s1.score); System.out.println(s1.age); //静态方法与非静态方法调用的区别 go(); s1.run(); } }
静态代码块
执行顺序:静态代码块>匿名代码块>构造方法
public class Person { /**匿名代码块 *创建对象时,自动创建,在构造器之前 */ { System.out.println("匿名代码块"); } /**静态代码块(可以用来加载初始化数据) *类一加载就执行 * 只执行一次 */ static { System.out.println("静态代码块"); } public Person(){ System.out.println("构造方法"); } public static void main(String[] args) { Person person = new Person(); System.out.println("============="); Person person2 = new Person(); } }
静态导入包
package oop.constructor.demo1; //静态导入包 import static java.lang.Math.random; public class Test { public static void main(String[] args) { //System.out.println(Math.random());非静态导入包调用方法 System.out.println(random()); } }

浙公网安备 33010602011771号