zl程序教程

您现在的位置是:首页 >  其他

当前栏目

Static、Final关键字详解

2023-03-31 11:01:25 时间

1.Static

详情见下面代码讲解
点击查看代码
package com.Tang.oop.demo07;

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.score);
        System.out.println(s1.age);
        //run();//在静态方法中不能直接调用非静态方法
        new Student().run();//必须得通过new一个对象来调用
    }
}

2.代码块(静态,匿名,构造)

点击查看代码
package com.Tang.oop.demo07;

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

运行结果

3.final

final为常量,被其修饰的类就无法被继承,也就是不能有子类当父类Person被final修饰时,子类Student就无法在继承Person如下图