2

I am new to java and I've come across this question: in C/C++ we have const modifier which makes function parameters Immutable, Therefore user is confident that the arguments they pass wont change.

But I could not find the same thing in java. Sure final modifier makes the field assignable only once and it works fine to some extent. But what about Objects that I need to modify before sending?(I could make a final copy of the Object but I don't find it good enough. correct me if I'm wrong). what about Object's fields? how we can pass an Object in a way that we would be confident of the integrity of the Object?

Dana Afa
  • 43
  • 4
  • You might want to look at https://stackoverflow.com/questions/279507/what-is-meant-by-immutable – Progman Mar 01 '20 at 17:58

1 Answers1

3

In Java immutability is an intrinsic property of the type.

For instance String is immutable. No need for const. StringBuilder, CharSequence are, or maybe, mutable. So will need a copy. In these cases a quick .toString(). will do the job.

C++ defaults to an implicit copy for arguments. Copying is in someways a better version of immutability. const & is kind of effectively a way of getting a copy without paying for it. (I'm sure many people will strongly disagree with this paragraph.)

Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
  • Thanks! although its still a bit strange for me to make a final-copy of the object. something I found interesting was that there some classes that have sub-classes which overrides the set functions and then passes it thus making it impossible to modify. How do you find this solution? and just a minor question, making a final copy of an object makes the fields of the field immutable as well? – Dana Afa Mar 01 '20 at 17:58
  • @DanaAfa In many cases it makes sense to make the only version of a type immutable. Perhaps with a builder, although they are a faff. – Tom Hawtin - tackline Mar 01 '20 at 18:00