What is Stateless Object in Java?
Stateless object is an instance of a class without instance fields (instance variables). The class may have fields, but they are compile-time constants (static final).
A very much related term is immutable. Immutable objects may have state, but it does not change when a method is invoked (method invocations do not assign new values to fields). These objects are also thread-safe.
The concept of stateless object is highly coupled with concept of side effects. Shortly, that is the object that has no fields underneath which could have different values, dependently on different order of method calls.
In simple terms state of object means value of internal variables in that object.
Stateful - state of object can be changed, means internal values off member variables of that object can be changed
How values can be changed?
By setting the value.
When can you set that value? When the variable is not final..
So, to make the class stateless, make the variable final, so that the value of that variable can't be changed neither in setter not in another method. It can be used only for computing.
If the object doesn't have any instance fields, it it stateless. Also it can be stateless if it has some fields, but their values are known and don't change.
This is a stateless object:
class Stateless {
void test() {
System.out.println("Test!");
}
}
This is also a stateless object:
class Stateless {
//No static modifier because we're talking about the object itself
final String TEST = "Test!";
void test() {
System.out.println(TEST);
}
}
This object has state, so it is not stateless. However, it has its state set only once, and it doesn't change later, this type of objects is called immutable:
class Immutable {
final String testString;
Immutable(String testString) {
this.testString = testString;
}
void test() {
System.out.println(testString);
}
}