Why is this class mutable? [duplicate]

  • A+
Category:Languages

This question already has an answer here:

public class Test {     private final String url;     public Test(String url) {         this.url = url;     }     public String getUrl() {         return url;     } } 

The Test class has:

  1. Only one instance variable which is private and final.
  2. No setters.
  3. The only way to initialize the instance variable is through the constructor.
  4. And once the URL is set, it can't be modified even in getUrl even if that method is overridden by any subclass of Test.

But a book that I am reading says the above Test class is mutable because:

  • Neither class is final so that it can be extended, and a subclass can override instance methods. But the Test class does not really have any instance methods other than the constructor.

  • Nor is the constructor private.

Can you please help me in understanding why the Test class is mutable?

 


An arbitrary instance of Test isn't guaranteed to be immutable, although direct instances of Test are. But consider this subclass:

public class MutableTest extends Test {         private int mutable;         public MutableTest(String url) {                 super(url);         }          @Override         public String getUrl() {                 return super.getUrl() + mutable++;         } } 

Then you can write something like this:

Test instance = new MutableTest("http://example.com/"); String firstGet = instance.getUrl(); String secondGet = instance.getUrl(); assertEquals(firstGet, secondGet); // Boom! 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: