How to enforce immutability to prevent the modification of values in Java

1 Answer

0 votes
// Immutable User Class in Java (Enforce Immutability)

public class Main {

    // Immutable User class
    static final class User {
        // Fields are private and final → cannot be modified after construction
        private final int id;
        private final String name;

        // Constructor initializes all fields exactly once
        public User(int id, String name) {
            this.id = id;
            this.name = name;
        }

        // Getter methods provide read‑only access
        public int getId() {
            return id;
        }

        public String getName() {
            return name;
        }

        // No setters → immutability enforced
    }

    public static void main(String[] args) {

        // Create an immutable User object
        User u = new User(42, "James");

        System.out.println("ID: " + u.getId());
        System.out.println("Name: " + u.getName());

        // The following lines would cause compile‑time errors:
        // u.id = 100;          // ERROR: id is final + private
        // u.name = "John";      // ERROR: name is final + private
        // u.setName("John");    // ERROR: no setter exists

        // The object is fully immutable
    }
}



/* 
run:

ID: 42
Name: James

*/

 



answered 13 hours ago by avibootz
...