代码改变世界

Day30static

2022-09-01 12:31  rebirthhhh  阅读(11)  评论(0编辑  收藏  举报

static

package oop.demo2;

//static 静态
public class Student {

    private static int age;//静态的变量  多线程
    private double score;//非静态的变量

    public void run(){

    }

    public static void go(){

    }

    public static void main(String[] args) {
        new Student().run(); //非静态方法需要先new一个
        Student.go();// go(); 静态方法可以直接调用


        //Student s1 = new Student();
        //System.out.println(Student.age);
        //System.out.println(s1.age);
        //System.out.println(s1.score);

    }
}

package oop.demo2;

public class Person {
    {
        //代码块(匿名代码块)
    }

    static {
        //静态代码块,永久只执行一次,而且先执行,可以赋一些初始值
    }

    {
        System.out.println("匿名代码块");
    }

    static {
        System.out.println("静态代码块");
    }

    public Person() {
        System.out.println("构造方法");
    }

    public static void main(String[] args) {
        Person person = new Person();
    }
}

//类被final修饰之后就不能被继承了
package oop.demo2;
//静态导入包 上面调用了下面可以不用写Math
import static java.lang.Math.random;

public class Test {
    public static void main(String[] args) {
        System.out.println(Math.random());//返回随机数
    }
}