static、final关键字

本文详细介绍了Java中static和final关键字的使用方法及其特性。包括static如何实现伪全局变量的效果,其初始化过程及static方法的特点;同时深入探讨了final关键字的意义,如常量的定义、final变量与引用的特点以及final方法与类的不可继承性和不可覆盖性。

static

在Java中并不存在全局变量的概念,但是我们可以通过static来实现一个“伪全局”的概念,在Java中static表示“全局”或者“静态”的意思,用来修饰成员变量和成员方法,当然也可以修饰代码块。

static的初始化

初始化:http://www.cnblogs.com/maying3010/p/5866128.html

由于static代表 静态 的意思,所以static只初始化一次
public class TestClass {
public static void main(String[] args) {
People people1 = new People();
System.out.println(people1.flag1);
System.out.println(people1.flag2);
People people2 = new People();
System.out.println(people2.flag1);
System.out.println(people2.flag2);
System.out.println(people1.random);
System.out.println(people2.random);
}
}
class People {
static Random random = new Random();
int flag1 = random.nextInt(10000);
static int flag2 = random.nextInt(10000);
}

class Man extends People{
static Random random = new Random();
int flag1 = random.nextInt(10000);
static int flag2 = random.nextInt(10000);
}
2776
3675
8809
3675
java.util.Random@4554617c
java.util.Random@4554617c

static方法

1. 该方法仅能调用static成员(data、functon)
2. 不能this、super
3. 不能被覆盖
4. 关闭动态绑定

final(常量)

Java关键字final有“这是无法改变的”或者“终态的”含义。

final数据

1. 编译期常量非编译期常量
编译器常量的特点就是:它的值在编译期就可以确定。比如:
final int i = 5;
再傻的编译器也能在编译时看出它的值是5,不需要到运行时。对于运行时常量,它的值虽然在运行时初始化后不再发生变化,但问题就在于它的初始值要到运行时才能确定。 比如:
Random rand = new Random(47);
final int i4 = rand.nextInt(20);
public class TestClass {
    public static void main(String[] args) {
        System.out.println(People.flag1);
        System.out.println("---------------------");
        System.out.println(People.flag2);
    }
}
class People {
    static {
        System.out.println("People已编译");
    }
    static Random random = new Random(47);
    static final int flag1 = random.nextInt(10);   //非编译期常量
    static final int flag2 = 1;            //编译期常量
} output:
People已编译
8
---------------------
1
2. 基本数据、引用 :
final 基本数据    指的是该基本数据的不能改变 。
final 引用    指的是该引用不能指向其他对象
3. 空白final:
可以首先空白final,再构造器中完成final的赋值
public class TestClass {
    public static void main(String[] args) {
        StringBuffer stringBuffer = new StringBuffer("hello");
        People people = new People(10,stringBuffer);
        System.out.println(people.flag);
        System.out.println(people.stringBuffer);
    }
}
class People {
    final int flag;
    final StringBuffer stringBuffer;
    People(int flag,StringBuffer stringBuffer){
        this.flag =flag;
        this.stringBuffer = stringBuffer;
    }
} output:
10
hello

final方法与类

final方法:该方法不能被覆盖、不能被继承、关闭动态绑定。
final类:该类不能被继承

转载于:https://www.cnblogs.com/maying3010/p/5866609.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值