静态方法和代码块
static
package com.oop.Demo07;
//static修饰 静态方法,静态属性
public class Student {
private static int age;//静态变量
private double score;//非静态变量
public static void main(String[] args) {
Student s1 = new Student();
System.out.println(Student.age);
System.out.println(s1.age);
System.out.println(s1.score);
}
}
静态方法可以调用静态方法,非静态方法可以调用静态方法,但是静态方法不可以调用非静态方法,非静态方法也不可以调用自身,因为非静态方法只有当对象被new出来以后才会加载
代码块
package com.oop.Demo07;
public class Person {
{
System.out.println("匿名代码块");
}
//只执行一次
static {
System.out.println("静态代码块");
}
public Person() {
System.out.println("构造方法");
}
public static void main(String[] args) {
Person person01 = new Person();
System.out.println("==============");
Person person02 = new Person();
}
}
结果:

静态导入方法
package com.oop.Demo07;
//静态导入包
import static java.lang.Math.PI;
import static java.lang.Math.random;
public class Test {
public static void main(String[] args) {
System.out.println(random());
System.out.println(PI);
}
}

浙公网安备 33010602011771号