为什么标记为 final 的对象可以被修改并在 Java 中调用非 final 方法?

Why an object marked as final can be modified and call non-final method in Java?

我是 Java 的新手,我有 C++ 背景。

我认为 Java 中的 final 与 C++ 中的 const 一样,但我猜不是。

对象在 C++ 中初始化为 const,只能调用 const 方法,不能更改对象中的字段。

但是在我下面的代码中,我可以在 pet 中赋值。即 pet.id = new ObjectId(newPetId);.

private void addPet() {
    progressBar.setVisibility(View.VISIBLE);

    final Pet pet;

    try {
        // Locally add and save pet.
        pet = getPetFromUserInput();

    } catch (InvalidInputException e) {
        progressBar.setVisibility(View.GONE);
        return;
    }

    pet.id = new ObjectId(); // Modify field member directly.
    pet.updateName("MyPet"); // Call non-final method.
}

在Java中,关键字"final"只是表示一旦初始化,就不能改变变量的值。 例如,

final int x = 0;`
//You can't do this!!!
int x=5

与那个变量调用方式无关

参考 Erik 在评论中的回答,我找到了一个针对 C++ 程序员的简单解释。

Java 中的

Pet pet; 类似于 C++ 中的 Pet* pet;

Java 中的

final Pet pet; 类似于 C++ 中的 Pet * const pet;,它使指针成为 const 而不是值本身。

请注意,Java 和 C++ 存在细微差别。

在 C++ 中,您必须在声明 const 变量时分配一个值,但在 Java 中,它允许您稍后再做一次。

在java中"final"表示这个

1.If 你在 class 之前使用 "final",那么这意味着没有机会为那个 class 创建子class。

public final class Person {
void getName() {

}

}

那你就不能这样创作了

public class Man extends Person{
}
"The type Man cannot subclass the final class Person" will be shown
  1. 如果你在方法前写 "final" 那么

    public  class Person {
    final void getName() {      
    }   
    }
    

然后你可以为这个人创建 subclass class 但你不能覆盖 subclass.

中的 getName()
public class Man extends Person{

@Override
void getName() {
    // TODO Auto-generated method stub
    super.getName();
}

}

"Cannot override the final method from Person" will be shown.
  1. 如果你在class中的变量前写"final",那么你不能改变那个变量的值

示例:

public  class Person {
public final String name;
void getName() {

}   
}

那么在子class中,你不能修改值。

public class Man extends Person{

public void getName() {
    name = "child";
}

}
"The final field Person.name cannot be assigned" will be shown

所有这些都将在编译时显示。

希望对您有所帮助。