Java inheritance does not allow inherited classes to be immutable class final class

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.