简体   繁体   English

非最终的-不可变的类

[英]non final - immutable classes

I have read and have always been told that immutable classes must be final . 我已阅读并始终被告知不变类必须是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 . 在此链接中( 为什么要在Java中将一个不可变的类声明为final? ),如果不可变的类方法是final并且不能被覆盖,该怎么办 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. 例如,Guava的ImmutableList类不是最终的,但它是不可变的,如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. 让我从Java类本身中获取一个这样的例子。“ BigInteger”类是不可变的,但不是最终的。

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. 让我们从JVM的角度考虑,从JVM的角度来看,所有线程都必须共享对象的相同副本,并且在任何线程访问它之前,它都已完全构建,并且对象的状态在其构建后不会改变。

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 http://javaunturnedtopics.blogspot.in/2016/07/can-we-create-immutable-class-without.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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