0

Can non-final arguments or returned objects make an object mutable?

What difference does it make by changing this:

public final class MyImmutableClass {

public final MyObject doStuff(final SomeObject someObject) {
    ...
}

}

to this:

public final class MyImmutableClass {

public MyObject doStuff(SomeObject someObject) {
    ...
}

}

When the goal is to make MyImmutableClass truly immutable.

After appling the change, is MyImmutableClass still considered immutable? If not, what state could be altered by making the changes?

Hooli
  • 1,135
  • 3
  • 19
  • 46
  • 2
    IIRC making a class final doesn't affect mutability. It just means that the class can't be subclassed – Tim Sep 04 '15 at 09:48
  • 1
    possible duplicate of http://stackoverflow.com/questions/2236599/final-keyword-in-method-parameters ? – Sweeper Sep 04 '15 at 09:51

1 Answers1

3

First of all a class is never immutable, an instance of a class could be. Next,

public final MyObject doStuff(final SomeObject someObject) {

Here, you can't change the reference someObject to point to some other instance of SomeObject inside the method. This guarantees that you are always using the argument passed by the caller.

Next, final in a method signature ensures that it cannot be overridden (which is redundant if the class itself is marked as final.)

TheLostMind
  • 35,966
  • 12
  • 68
  • 104