static 关键字

static 关键字

  • 用static声明的成员变量为静态成员变量,也成为类变量。类变量的生命周期和类相同,在整个应用程序执行期间都有效。

  • 注意:

    • static修饰的成员变量和方法,从属于类
    • 普通变量和方法从属于对象
    • 静态方法不能调用非静态成员,编译会报错
public class Student extends Person{
    private static int age = 10; //静态变量
    private double score = 80.6;

    public static void main(String[] args) {
        Student student = new Student();
        System.out.println(student.age);
        System.out.println(student.score);
        System.out.println(Student.age);
        //System.out.println(Student.score);   不能直接用类名去调用非静态变量
    }
}

//10
80.6
10
public class Student extends Person{
    private static int age = 10; //静态变量
    private double score = 80.6;

    public static void print(){
        System.out.println("静态方法");
    }

    public void add(){
        System.out.println("非静态方法");
    }
    public static void main(String[] args) {
        Student student = new Student();
        Student.print();
        //Student.add();    不能直接用类名去调用非静态方法
        student.print();
        student.add();
    }
}
//静态方法
静态方法
非静态方法
public 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();
    }
}

//静态代码块
代码块(匿名代码块)
执行构造方法
================================
代码块(匿名代码块)
执行构造方法
posted @ 2021-04-09 17:34  saxon宋  阅读(36)  评论(0)    收藏  举报