您的位置:首页 > 编程语言 > Java开发

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

2015-11-02 17:09 411 查看
这一章节我们将来讨论一下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的特性。

这一章节就到这里,谢谢。
-----------------------------------
目录
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java