面向对象14:static关键字详解

非静态的方法可以调用静态方法里的所有东西,静态方法里可以调用静态方法的,但是不能直接调用非静态方法的

1.static静态属性与方法
package com.oop.demo09;

//static

public class Student {

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

    //非静态方法
    public void run(){
        go();
    }
    //静态方法
    public static void go(){

    }


    public static void main(String[] args) {
        Student s1 = new Student();

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

        //调用静态方法
        Student.go();
        go();

    }
}

2.代码块执行顺序:

2.代码块
执行顺序 —>1
//静态代码块 只执行一次
static {
}
执行顺序 —>2
//代码块(匿名代码块)
{
}
执行顺序 —>3
//构造方法
public Person() { }

package com.oop.demo09;

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 person1 = new Person();
        System.out.println("===========================");
        Person person2 = new Person();
    }
}

结果:

3.静态导入包
package com.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 @ 2020-08-31 14:32  nkndlawn  阅读(105)  评论(0)    收藏  举报