Search code examples
javaandroidimmutabilityfinal

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


I am new to Java and I am from C++ background.

I thought final in Java works just like const in C++ but I guess not.

Object initiated as const in C++, only can call const methods and cannot change fields in the object.

But in my code below, I am able to assign value in pet. i.e. 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.
}

Solution

  • Referencing Erik's answer in comments, I found an easy explanation for C++ programmers.

    Pet pet; in Java is like Pet* pet; in C++.

    final Pet pet; in Java is like Pet * const pet; in C++ which makes the pointer const but not the value itself.

    Note that there is a subtle difference in Java and C++.

    In C++, you have to assign a value when declaring a const variable but in Java, it lets you do it later but only once.