Instance:
Public Final classaddress{Private FinalString Detail; Private FinalString postcode; //initializing two instance properties in a constructor method PublicAddress () { This. Detail = ""; This. Postcode = ""; } PublicAddress (String detail, string postcode) { This. Detail =detail; This. Postcode =postcode; } //provides getter methods for only two instance properties PublicString Getdetail () {return This. Detail; } PublicString Getpostcode () {return This. Postcode; } //override the Equals method to determine whether two objects are equal. Public Booleanequals (Object obj) {if(objinstanceofAddress) {Address ad=(Address) obj; if( This. Getdetail (). Equals (Ad.getdetail ()) && This. Getpostcode (). Equals (Ad.getpostcode ())) { return true; } } return false; } Public inthashcode () {returnDetail.hashcode () +Postcode.hashcode (); } Public Static voidMain (String args[]) {Address a=NewAddress (); Address b=NewAddress ("ABCD", "EFGH"); System.out.println ("A:" +a.getdetail () +a.getpostcode () +A.hashcode ()); System.out.println ("B:" +b.getdetail () +b.getpostcode () +B.hashcode ()); System.out.println (A.equals (b));}}
Results:
Cause Analysis:
in
Final
the declared method does not allow overwriting, nor does it allow changes, so using final,
we can devise a special kind of
"
Read-only
"
of the
"
Immutable Classes
"
.
Create
"
Immutable Classes
"
Object , the properties of this object cannot be changed .
and you cannot derive a new subclass from this class.
String
is a code
examples of types.
Immutable
"
class
"
the role
?
1, can be conveniently and safely used in multi-threaded environment,
2, access to them can not be locked, thus providing high performance.
Java inheritance does not allow inherited classes to be immutable class final class