static& final关键字详解\代码块\静态导入包

static& final关键字详解\代码块\静态导入包

package zaiyang.oop.demo07;

public class Student  {
    //static
    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(s1.age);//静态属性
        System.out.println(s1.score);//非静态属性,不能使用类名访问

        new Student().run();//非静态方法必须new类才能调用
        Student.go();//静态方法不用new就能调用,在当前类,非静态方法可以调用静态方法,静态方法可以调用静态方法。
        // 因为静态方法是和类一起加载的所以能调用,非静态方法没有加载所以无法调用。
    }
}
package zaiyang.oop.demo07;
//final为最终的,被final修饰的类无法被继承
public  final 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 person1 = new Person();
    }
}
/*
        静态代码块
        匿名代码块
        构造器方法
        =================================
        匿名代码块
        构造器方法

 */
package zaiyang.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);
    }
}
posted @ 2022-04-14 20:20  追风的羊  阅读(31)  评论(0)    收藏  举报