Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does it mean for an object to be transitively reachable from a final field?

This post talks about immutable objects being transitively reachable from a final field:

Immutability doesn't mean "does not change" in Java. It means "is transitively reachable from a final field, has not changed since the final field was set, and a reference to the object containing the final field did not escape the constructor".

For the the following code,

public class A() {
    private String myString;
    public A(String myString){
        this.myString = myString;
    }
    public String getMyStringAndYours(){
        return myString.concat("yours");
    }
}

are A instances transitively reachable from a final field? I think so because:
1. myString.value is final
2. myString is reachable from myString.value
3. An instance of A, a, is reachable from a.myString

Side question: Is a immutable?

like image 699
damat-perdigannat Avatar asked Mar 18 '23 17:03

damat-perdigannat


1 Answers

I would set aside transitively reachable for a moment and concentrate on the difference between final and immutability.

class MyObject {
int a;
void setA(int val){
a=val;
}
}

final MyObject obj = new MyObject(); 

now,since obj reference is final you will get a compilation error if you try to do

obj = new MyObject(); // you can't re-initialize a final reference.

But what you can do :

obj.setA(5); // perfectly valid.

you can change the state of object referenced by obj but cannot re-initialize obj to some other object

Now, if all fields inside MyObject were final and all setters were private (or absent), then there will be no way of doing

obj.setA(5); 

An immutable object is one whose internal state cannot change.

Now, coming back to transitively reachable. If Object A s composed of Object B and in-turn Object B has Object C (composition). Your Object A isn't truly immutable unless all transitively reachable objects are both immutable and final i.e, a.b.c here a ,b and ,c should be final to prevent re-assigning of reference to another object. Also, you should ensure that c is not shared (escapes the scope of A) whenever a is created. If it is shared, then any other object can change it.

Edit :

Strings are immutable so, you just need to make them final so that their enclosing class is immutable .

like image 132
TheLostMind Avatar answered Apr 26 '23 17:04

TheLostMind