引用不能变,其引用的对象本身可以变,比如:
- import org.junit.Assert;
- public class Person {
- public static void main(String[] args) {
- Person p1 = new Person("Bob", 20);
- Person p2 = new Person("Jobs", 34);
- final Person pFinal = p1;
- Assert.assertTrue(pFinal.age == 20);
- p1.setAge(25);
- Assert.assertTrue(pFinal.age == 25);
- pFinal.setAge(30);
- Assert.assertTrue(pFinal.age == 30);
- //pFinal=p2; //ERROR
- }
- private String name;
- private int age;
- public Person(String name, int age) {
- this.age = age;
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- }
复制代码 |