从头认识java-6.6 final(1)-属性域

这一章节我们将来讨论一下final。

1.特性

(1)对于常量,使用final之后就不可变

因为使用了final之后,id就没有了set方法,因此,不能对id进行操作,即便new之后直接对id进行操作也不可以

package com.ray.ch06;

public class Test {
	private final int id = 1;

	public int getId() {
		return id;
	}

	public static void main(String[] args) {
		// new Test().id=2;//error
	}
}

(2)对于对象,使用final之后是引用不变,但里面的值可能改变

package com.ray.ch06;

public class Test {
	private final Value value = new Value();

	public Value getValue() {
		return value;
	}

	public static void main(String[] args) {
		Value value = new Test().getValue();
		System.out.println("before set i -> final value:" + value.getI());
		value.setI(2);
		System.out.println("after set i -> final value:" + value.getI());
	}
}

class Value {
	private int i = 0;

	public int getI() {
		return i;
	}

	public void setI(int i) {
		this.i = i;
	}

}

输出:

before set i -> final value:0
after set i -> final value:2


跟上一个特性的代码相似,value也是没有set方法,因此不能对其设置新的引用。

但是,我们可以get出value的引用,然后设置里面的值,通过输出结果即可看到。


(3)联合static一起使用

package com.ray.ch06;

public class Test {
	private static final int id = 0;
	private final String name = "abcd";
	private final Value value = new Value();
	private static final Value value2 = new Value();

	public static Value getValue2() {
		return value2;
	}

	public Value getValue() {
		return value;
	}

	public static int getId() {
		return id;
	}

	public String getName() {
		return name;
	}

	public static void main(String[] args) {
		Test test1 = new Test();
		Test test2 = new Test();
		System.out.println(test1 == test2);
		System.out.println(test1.getName() == test2.getName());
		System.out.println(test1.getValue() == test2.getValue());
	}

}

class Value {
}

输出:

false
true
false


跟static联合使用,可以通过Test.value来取得,因此引用必定相同。

但是如果不是跟static联合使用,就会出现一个情况,对象的引用不同。

根据上面的输出结果:字符串在使用final后,两者都是引用同一个字符串,但是Value类在使用final后,两个引用是不同的。


总结:这一章节主要讲述了final的特性。


这一章节就到这里,谢谢。

-----------------------------------

目录



  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 10
    评论
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值