简体   繁体   中英

non final - immutable classes

I have read and have always been told that immutable classes must be final . but i was wondering if it is possible to have a non final class object as immutable one. in this link ( Why would one declare an immutable class final in Java? ) what if the immutable class methods are final and cannot be overriden . And if all the members of the class are final, then also the object of that class can be immutable( unless they reference to a mutable object). Please tell me if am wrong and get ticked :)

如果可以扩展一个不可变的类(这意味着它不是最终的),则可以将可变属性添加到子类中,这将使您的子类可变,因此基类也将是可变的,因为它可以具有可变性子类。

An immutable class doesn't necessarily need to be final, but you need to prevent it from being subclassed, eg by not having public or protected constructors.

For example, Guava's ImmutableList class isn't final, but it is immutable, as described in the Javadoc.

For creating immutable class it is not mandatory to mark the class as final.

Let me take one of such example from java classes itself "BigInteger" class is immutable but its not final.

Actually Immutability is a concept according to which ones the object created then it can not be modified.

Let's think from JVM point of view, from JVM point of view all threads must share the same copy of the object and it is fully constructed before any thread accesses it and the state of the object doesn't change after its construction.

Immutability means there is no way yo change the state of the object once it is created and this is achieved by three thumb rules which makes the compiler to recognize that class is immutable and they are as follows :-

all non private fields should be final make sure there is no method in the class that can change the fields of the object either directly or indirectly any object reference defined in the class can't be modified outside from the class For more information refer to the below URL

http://javaunturnedtopics.blogspot.in/2016/07/can-we-create-immutable-class-without.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM