What does it mean that an object must be in transit from a destination field?

This post suggests that immutable objects are transitively reachable from a finite field:

Invariance does not mean that it "does not change" in Java. This means that "it is transitable from the final field, has not changed since the installation of the final field, and the link to the object containing the final field has not left the constructor."

For the following code

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

Are there cases transitively reachable from a finite field? I think so because:
1. myString.value final
2. myStringreachable from myString.value
3. Instance A, aavailable froma.myString

Side question: aunchanged?

+4
3

. :

public class SomeBean {
    private String a;
}

public class SomeOtherBean {
    private SomeBean someBean;
    ...
}

public class Foo {
    private final SomeOtherBean someOtherBean;
    private /* non-final */ SomeOtherBean someOtherBean2;
}

Foo.someOtherBean.someBean Foo.someOtherBean.someBean.a , Foo.someOtherBean , Foo.someOtherBean Foo.someOtherBean.someBean Foo.someOtherBean.someBean.a , .

, Foo.someOtherBean2.someBean Foo.someOtherBean2.someBean.a not , Foo.someOtherBean .

+1

final immutability.

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

final MyObject obj = new MyObject(); 

, obj final ,

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

:

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

, obj, obj -

, MyObject final, ( ),

obj.setA(5); 

immutable - , .

, . A, B B , C (). A , , a.b.c a, b , c , . , , c ( A) , . , .

:

, , .

+5

Awill be "immutable." Since the field myStringcannot be changed after construction (at least in the context provided by the code), the state Adoes not change, making it unchanged.

In addition, String # concat (String) does not change state String, as indicated in the documentation, it creates a new String, making sure that String is immutable and remains Aimmutable.

+1
source

All Articles