Java: questions about immutability and finality

I'm reading "effective Java"

In the project of minimizing variability, Joshua Bloch discussed the problem of making a class immutable

>Don't provide any way to modify the state of an object – that's good. > Ensure that the class cannot be extended. – Do we really need to do this? > Let all areas ultimately – do we really need to do this?

For example, suppose I have an immutable class,

class A{
private int a;

public A(int a){
    this.a =a ;
}

public int getA(){
    return a;
}
}

How does the curriculum extending from a affect the invariance of a?

Solution

like this:

public class B extends A {
    private int b;

    public B() {
        super(0);
    }

    @Override
    public int getA() {
        return b++;
    }
}

Technically, you don't want to modify the fields inherited from a, but in an immutable object, the repeated calls of the same getter should produce the same number, which is not the case here

Of course, if you insist on using the rule #1, you are not allowed to create this override However, you are not sure whether others will follow the rule If one of your methods takes a as a parameter and calls geta () on it, others can create class B and pass its instance to your method as described above; Your method will then modify the object unknowingly

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>