开发者

What is a "Mutable class" in OOP?

The standard class...is开发者_开发技巧 it mutable or not?


It depends strongly on the language. Some of them do not even allow mutable objects.

Many mainstream languages default to being highly mutable, depending on what members you expose on your class's public interface. In at least a couple mainstream languages (particularly dynamic languages) it is really hard to make immutable objects.

See a definition of (im)mutable for more information:

In object-oriented and functional programming, an immutable object is an object whose state cannot be modified after it is created. This is in contrast to a mutable object, which can be modified after it is created.


A mutable class is one that can change its internal state after it is created.

Generally speaking, a class is mutable unless special effort is made to make it immutable.


A mutable class is a class that has a changeable state. for example, if you have a class representing a number, Number, then it is mutable if you can do something like

Number num(4);
num.set(5);

i.e., change the internal state.

from Wikipedia:

In object-oriented and functional programming, an immutable object is an object whose state cannot be modified after it is created. This is in contrast to a mutable object, which can be modified after it is created. An object can be either entirely immutable or some attributes in the object may be declared immutable; for example, using the const member data attribute in the C++ programming language.


I am a C/C++/C# and now Java developer. In C etc. you can pass a instance of a class by reference. I think that makes a class in C etc. default mutable. In Java if you pass a Class its not default mutable. Its a copy (always by value), so the content of the Class can not change in the function. I noticed that some Objects when you use them in a Java class and then pass that class to a function, you can change the content of the object, so that object is mutable. Please confirm if I see it right like that?


"Usually" (as in usual languages) it is mutable.


Classes are typically not mutable (though some languages deviate from this). The objects that you create from classes, on the other hand, are often mutable if they include state and you do not take special care to prevent anyone from changing that state after object creation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜