What is Stateless Object in Java?
Solution 1:
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.
Solution 2:
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);
}
}