Home >Java >javaTutorial >How Does Java's `final` Keyword Affect Object Modification?
In Java, the "final" keyword is used to declare variables with immutable values. However, you may encounter scenarios where you can still modify an object assigned to a final variable. This behavior requires a deeper understanding of final's functionality.
Instance Variables:
Static Variables:
Consider the following code:
import java.util.ArrayList; import java.util.List; class Test { private final List foo; public Test() { foo = new ArrayList(); foo.add("foo"); // Modification-1 } public static void main(String[] args) { Test t = new Test(); t.foo.add("bar"); // Modification-2 System.out.println("print - " + t.foo); } }
Java 1.8 introduced the concept of "effectively final" variables. These are local variables that are effectively immutable within nested classes or anonymous inner classes. While they don't use the "final" keyword, they cannot be reassigned.
The above is the detailed content of How Does Java's `final` Keyword Affect Object Modification?. For more information, please follow other related articles on the PHP Chinese website!