In profile management systems, distinguishing between active (modifiable) and archived (read-only) records is crucial for data consistency. This project highlights the Structural Differences between Regular Classes and Records. We implement a FlexibleUser class with setters to allow state changes and a FixedUser record to enforce strict immutability. This comparison demonstrates how records protect data from modification, whereas regular classes provide the flexibility needed for dynamic updates.
- Mutable State: Implemented a standard class with setters for name and age.
- Immutable Contract: Used a record to ensure fields are final and setters are absent.
- Compile-time Safety: Verified that records block any attempt to change their components.
- Java 16+ (Classes, Records, Mutability Patterns)
- FlexibleUser: A standard Java class with a constructor, getters, and setters.
- FixedUser: A record providing a fixed data snapshot.
- ProfileComparisonApp: The entry point for testing mutability limits.
*** The code will not compile if lines attempting to modify the record are active.
Flexible profile (before): FlexibleUser[name=Greg, age=30]
Flexible profile (after): FlexibleUser[name=Piter, age=25]
Fixed profile (record): FixedUser[name=Hana, age=28]
Project Structure:
JavaBasics_Task_404/
├── src/
│ └── com/yurii/pavlenko/
│ ├── app/
│ │ └── ProfileComparisonApp.java
│ └── profiles/
│ └── models/
│ ├── FlexibleUser.java
│ └── FixedUser.java
├── LICENSE
├── TASK.md
├── THEORY.md
└── README.md
Code
package com.yurii.pavlenko.app;
import com.yurii.pavlenko.profiles.models.FlexibleUser;
import com.yurii.pavlenko.profiles.models.FixedUser;
public class ProfileComparisonApp {
public static void main(String[] args) {
FlexibleUser flexible = new FlexibleUser("Greg", 30);
System.out.println("Flexible profile (before): " + flexible);
flexible.setName("Piter");
flexible.setAge(25);
System.out.println("Flexible profile (after): " + flexible);
FixedUser fixed = new FixedUser("Hana", 28);
System.out.println("Fixed profile (record): " + fixed);
/*
* UNCOMMENTING THE LINES BELOW WILL CAUSE COMPILATION ERRORS:
* * fixed.setName("Mary"); // Error: method not found
* fixed.age = 29; // Error: field is final
*/
}
}package com.yurii.pavlenko.profiles.models;
public record FixedUser(String name, int age) {
}package com.yurii.pavlenko.profiles.models;
public class FlexibleUser {
private String name;
private int age;
public FlexibleUser(String name, int age) {
this.name = name;
this.age = age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "FlexibleUser[name=" + name + ", age=" + age + "]";
}
}This project is licensed under the MIT License.
Copyright (c) 2026 Yurii Pavlenko
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files...
License: MIT