1<!doctype html>
2<html lang="en">
3<head>
4  <title>Value-based Classes</title>
5  <link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">
6</head>
7<body>
8<h2 id="ValueBased">Value-based Classes</h2>
9
10Some classes, such as <code>java.util.Optional</code> and
11<code>java.time.LocalDateTime</code>, are <em>value-based</em>.  Instances of a
12value-based class:
13<ul>
14    <li>are final and immutable (though may contain references to mutable
15        objects);</li>
16    <li>have implementations of <code>equals</code>,
17        <code>hashCode</code>, and <code>toString</code> which are computed
18        solely from the instance's state and not from its identity or the state
19        of any other object or variable;</li>
20    <li>make no use of identity-sensitive operations such as reference
21        equality (<code>==</code>) between instances, identity hash code of
22        instances, or synchronization on an instances's intrinsic lock;</li>
23    <li>are considered equal solely based on <code>equals()</code>, not
24        based on reference equality (<code>==</code>);</li>
25    <li>do not have accessible constructors, but are instead instantiated
26        through factory methods which make no committment as to the identity
27        of returned instances;</li>
28    <li>are <em>freely substitutable</em> when equal, meaning that interchanging
29        any two instances <code>x</code> and <code>y</code> that are equal
30        according to <code>equals()</code> in any computation or method
31        invocation should produce no visible change in behavior.
32    </li>
33</ul>
34
35<p>A program may produce unpredictable results if it attempts to distinguish two
36    references to equal values of a value-based class, whether directly via reference
37    equality or indirectly via an appeal to synchronization, identity hashing,
38    serialization, or any other identity-sensitive mechanism.  Use of such
39    identity-sensitive operations on instances of value-based classes may have
40    unpredictable effects and should be avoided.</p>
41</body>
42</html>
43