static关键字详解

static关键字详解

  • 静态变量可通过类名调用,但是非静态变量只能通过对象调用
  • 非静态方法里可以去调用静态方法,静态方法里可以去调用静态方法,但不能调用非静态方法静态代码块。
  • 程序会先执行静态代码块,而且只执行一次
  • 静态导入包
  • 被final修饰的类不能被继承
package com.oop.demo05;

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();

    }
}

 


 

package com.oop.demo05;

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(s1.age);
        System.out.println(Student.age);//因此,静态变量可通过类名调用
        System.out.println(s1.score);//但是非静态变量只能通过对象调用

        //非静态方法里可以去调用静态方法,静态方法里可以去调用静态方法,但不能调用非静态方法
        new Student().run();
        Student.go();//也可以直接写go()
        //run();不合法


    }
}

package com.oop.demo05;
//静态导入包
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-16 17:51  胖虎9  阅读(29)  评论(0)    收藏  举报