Java 关键字Static和Final

1. static

1.1 static可以修饰变量和方法,static修饰的变量和方法属于类,即所有对象共享这个变量、方法。

1.2 一个对象修改static变量,修改后的结果其他变量也可以看到。

1.3 static修饰的方法可以使用"类名.方法名"的方式调用

1.4 静态块,static修饰的类变量最先初始化,所以可以使用static{   }的形式把要定义类变量集中在一起,使程序可读性更好,下例:

static Person p1 = new Person();

static Person p2 = new Person();

等价于:

static Person p1,p2;

static{

        p1 = new Person();

        p2 = new Person();

}

 

2. final

2.1 final修饰的变量称为常量,只能经过一次赋值,即有如下两种常见写法:

    final int a = 1; // 在定义变量时赋值

    final int a;  a = 1; // 先定义再赋值

    final Person p1 = new Person();// final修饰的类变量,则p1引用一个对象后,不能再对p1进行赋值,引用其他对象

2.2 final修饰方法参数,则该参数在生存期期间不能被修改

2.3 final修饰方法,则该方法不能被重写

2.4 final修饰类,则该类无法被继承

 

参考:https://blog.csdn.net/happybruce8023/article/details/79943997

猜你喜欢

转载自blog.csdn.net/Faustine___/article/details/93604208