Vince
Vince

Reputation: 15146

Are Value Classes allowed to exhibit change?

The doc for Value Based Classes specify:

Instances of a value-based class:

  • are final and immutable (though may contain references to mutable objects);

If I defined a value class Foo, which had a mutable member Bar:

value class Foo {
    Bar bar; // Bar is a mutable type
}

Then introduced a method which queried one of Bar methods, which may return different results (for example, an int value which may change):

public int number() {
    return bar.number(); // may return different results!
}

Would this be an improper use of a Java value class?

JEP 401 mentions:

Simple domain values are commonly shared throughout a program, but their fields are final, so different parts of a program that have references to a given object will never observe any changes in it.

Does the fact that the change can be observed through Foo#number() mean that it is an improper to use a value class?

Upvotes: 1

Views: 127

Answers (0)

Related Questions