1
votes

From http://docs.oracle.com/javase/tutorial/essential/concurrency/imstrat.html :

Don't provide "setter" methods — methods that modify fields or objects referred to by fields. Make all fields final and private. Don't allow subclasses to override methods. The simplest way to do this is to declare the class as final. A more sophisticated approach is to make the constructor private and construct instances in factory methods. If the instance fields include references to mutable objects, don't allow those objects to be changed: Don't provide methods that modify the mutable objects. Don't share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.

A class called Employee has a Instance variable a of type Address
My Question : what should be done to make this class immutable ( condition: I want to return the same instance variable a from getAddress() getter).
Should I make the address class immutable ?

Note: I understand defensive copy, but do not want to use this

3
Your quoted text explains it quite well: all fields should be final at the very least. What is the difficuly?fge
And the attributes of your class that are objects must be of immutable classes as well.SJuan76

3 Answers

0
votes

you can make address of employee as final variable, so it has to be instantiated before the constructor finishes execution. so you can modify constructor of employee so that it always takes address param n inits instance address variable. once set u can't assign a new address obj to already init address variable.

0
votes

A class called Employee has a Instance variable a of type Address My Question : what should be done to make this class immutable ( condition: I want to return the same instance variable a from getAddress() getter).

If you want to return exact same variable in getter - you cannot use copy there. But maybe you should implement equals() method for the Address class? that seems much better than relying on instance equality. You could use copies then, and be happy.

Should I make the address class immutable?

That's the only way to do it as you want it to do. But still you would need to make fileds of Address immutable. String is immutable by default, EMUNs as well, if you want to return something else - you would need to use defensive copies then.

0
votes

Yes, if you want to return the same instance stored in field a, your Address class needs to be immutable in order to make your Employee class immutable.

If you are willing to make a copy of the instance stored in field a and return that, then this does not have to be the case.