Java program to create an immutable class
Here's a Java program to create an immutable class:
public final class ImmutablePerson { private final String name; private final int age; public ImmutablePerson(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } }
This program creates a class called ImmutablePerson
which is designed to be immutable. An immutable class is a class whose instances cannot be modified after they are created. In this example, we have achieved immutability by making the class final
and making all the instance variables final
.
The class has two instance variables: name
and age
. Both of these variables are marked as final
, which means that they cannot be modified once they are set in the constructor.
The constructor takes two parameters: name
and age
. It sets the values of these parameters to the corresponding instance variables.
The class also has two methods: getName()
and getAge()
. These methods return the values of the name
and age
instance variables, respectively.
Since the ImmutablePerson
class is immutable, it can be safely shared between different parts of your program without worrying about unexpected changes to its state.
Here's an example of how to use the ImmutablePerson
class:
public class Main { public static void main(String[] args) { ImmutablePerson person = new ImmutablePerson("John", 30); System.out.println("Name: " + person.getName()); System.out.println("Age: " + person.getAge()); } }
In this example, we are creating a new ImmutablePerson
object with a name of "John" and an age of 30. We are then using the getName()
and getAge()
methods to retrieve the values of the name
and age
instance variables and printing them to the console.
This is just a simple example of how to create an immutable class in Java. You can modify the ImmutablePerson
class to include additional fields and methods to meet your specific needs.