Home >Java >javaTutorial >How Does Java's `final` Keyword Affect Object Modification?

How Does Java's `final` Keyword Affect Object Modification?

DDD
DDDOriginal
2024-12-15 18:04:14433browse

How Does Java's `final` Keyword Affect Object Modification?

How the "final" Keyword in Java Works (Modifying Objects)

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.

Variable Finality

Instance Variables:

  • Final instance variables can be initialized in the constructor.
  • Once initialized, they cannot be reassigned to a different object reference.
  • However, the contents of the object (e.g., if it's a collection) can still be modified.

Static Variables:

  • Final static variables must be initialized in the class declaration itself.
  • They cannot be initialized in constructors or methods.

Example

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);
  }
}
  • Modification-1: The final instance variable foo is initialized with a new ArrayList object in the constructor.
  • Modification-2: The add() method is used to modify the contents of the foo list, which is permitted.

Effectively Final in Java 1.8

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.

Subclassing and Overriding

  • Final classes: Cannot be subclassed.
  • Final methods: Cannot be overridden (in subclasses).
  • Final methods in superclasses: Can be overridden in subclasses.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn