Sample Program
1 PublicFinalclassAddress2 {3 Privatefinal String detail;4 Privatefinal String postcode;5 6 //initializing two instance properties in a constructor method7 PublicAddress ()8 {9 This. Detail ="";Ten This. Postcode =""; One } A PublicAddress (String detail, string postcode) - { - This. Detail =detail; the This. Postcode =postcode; - } - //provides getter methods for only two instance properties - PublicString getdetail () + { - return This. Detail; + } A at PublicString Getpostcode () - { - return This. Postcode; - } - //override the Equals method to determine whether two objects are equal. - Publicboolean equals (Object obj) in { - if(obj instanceof Address) to { +Address AD =(Address) obj; - if( This. Getdetail (). Equals (Ad.getdetail ()) && This. Getpostcode (). Equals (Ad.getpostcode ())) the { * return true; $ }Panax Notoginseng } - return false; the } + Public inthashcode () A { the returnDetail.hashcode () +Postcode.hashcode (); + } - $ Public Static voidMain (String args[]) $ { -Address A =NewAddress (); -Address B =NewAddress ("DSCFD","Fghgh"); the -System. out. println ("A:"+a.getdetail () +a.getpostcode () +A.hashcode ());Wuyi theSystem. out. println ("B:"+b.getdetail () +b.getpostcode () +B.hashcode ()); - WuSystem. out. println (a.equals (b)); - } About}
Results
Analysis:
Methods that are declared in final are not allowed to overwrite.
Variables declared in final are not allowed to change.
Using final, we can design a special "read-only" immutable class.
When an object of immutable class is created, the properties of this object cannot be changed, and new subclasses cannot be derived from this class. String is a typical example.
What is the use of immutable "classes"?
can be conveniently and safely used in multi-threaded environments, access to them can provide high performance without locking.
Instances in JDK: String
Interfaces and inheritance: Classes that are not allowed to inherit