What is the reason that the object marked final can be modified and called non final method in Java?
•
Android
I am a novice in Java. I come from C background
I think final in Java works like const in C, but I don't think so
Objects initialized with const in C can only call const methods, but cannot change the fields in the object
But in the following code, I can assign a value to pet. That is, 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.
}
resolvent:
Quoting Erik's answer in the comments, I found a simple explanation for C programmers
Pets are like pet * pet in Java; In C
The last pet in Java is like pet * const pet; In C, it makes the pointer const instead of the value itself
Note that there are subtle differences between Java and C
In C, you must assign a value when declaring the const variable, but in Java, it allows you to operate later, but only once
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码