It is easy to write constant classes. If the following points are true, then the class is constant:
Its Field is Final This class declares that Final does not allow this to reference to any fields included in the constructor any field containing variable objects (such as arrays, collections, or similar data:
It is privately from being returned or not otherwise publication to the calling program is the state of the referenced object without changing the unique reference configuration of the object they reference.
Guidelines for Writing Immutable classwriting immutable classes is easy. A class will be immutable if all of the folowing area true:
All of its fields are final The class is declared final The this reference is not allowed to escape during construction Any fields that contain references to mutable objects, such as arrays, collections, or mutable classes like Date:
Are private area.com to callers are the only reason do not changes That The Reference Do Not Change The State of The Reference Objects After Construction
Here is an invariant class file example: public final class immutableArrayholder {
PRIVATE FINAL INT [].
// Right Way to Write a Constructor - Copy The Array Public ImmutableArRayHolder (int [] Anarray) {this.theArray = (int []) Anarray.clone ();}
// Right Way to Write An Accessor - Don't Expose The Array Reference
Public int GetArrayLength () {return thearray.length;}
Public int GetArray (int N) {return thearray [n];}
// Right Way to Write an Accessor - Use Clone ()
Public int [] getArray () {return (int []) THEARRAY.CLONE ();}} The following is a test class for it: import junit.framework. *;
Public Class ImmutableArrayHolderTest Extends Testcase {Private ImmutableArrayHolder IAH; Private Int [] Array = {1, 2, 3, 4, 5};
Protected void setup () {iv = new immutableArrayHolder (array);
Public Static Testsuite Suite () {Return New TestSuite (ImmutableArRayholderTest.class);}
Public void testers () {array [3] = 5; assert.assertequals ((iah.getarray ()) [3], 5);} public static void main (string [] args) {junit.textui.teStrunner.run Suite ());}}
Test Results:
JUnit.framework.assertionFaileDerror: Expected: <4> But Was: <5>
At ImmutableArrayHoldert.Testequals (ImmutableArrayholdertest.java: 20)
At sun.reflect.nativeMethodAccessorImpl.invoke0 (Native Method)
At sun.reflect.nativeMethodaccessorImpl.Invoke (NativeMethodaccessorImpl.java: 39)
At sun.reflect.delegatingMethodaccessorImpl.invoke (DelegatingMethodAccessorImpl.java: 25)
At com.intellij.rt.execution.junit2.junitstarter.main (unknown source)
Through the test prove: Array has been copied by the Clone method, which is a non-change class.