在Brian Goetz的Java Concurrency in Practice中,为什么point class是Immutable,由DelegatingVehicleTracker使用

Pra*_*ore 3 java concurrency immutability

请让我知道为什么下面的类是不可变的,正如Java并发实践中所讨论的那样 - 作者Brian Goetz

@Immutable
public class Point {
    public final int x, y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}
Run Code Online (Sandbox Code Playgroud)

由于该类不是最终的,任何类都可以扩展它.但为什么它仍然是不可变的?

pet*_*rov 6

它是不可变的,因为一旦构造了它的实例,就无法以任何方式改变其内部状态.那是因为它没有设置器,x和y是最终的,即你不能改变/改变x或y值.

编辑(检查那个例子):

package test;

public class Test002 {

    public static void main(String[] args) {
        Point1 p1 = new Point1(4, 10);
        consume(p1);
    }

    public static void consume(Point p){
        System.out.println("=============");
        System.out.println(p.x);
        System.out.println(p.y);

        if (p instanceof Point1){
            System.out.println("=============");
            Point1 p1 = (Point1)p;
            p1.setX(5);
            p1.setY(11);
            System.out.println(p.x);
            System.out.println(p.y);
            System.out.println(p1.getX());
            System.out.println(p1.getY());          
        }
    }

}



class Point {
    public final int x, y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

class Point1 extends Point {
    private int x;
    private int y;

    public Point1(int x, int y) {
        super(x, y);
        this.x = x;
        this.y = y;
    }

    public void setX(int x) {
        this.x = x;
    }

    public void setY(int y) {
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @PramodKishore注意这里的评论:"你不需要让整个类最终只是getter ... public final int getValue()".在这里,我们没有吸气剂,x,y是最终的.所以我们覆盖了恕我直言.在templatetypedef的回答后仔细阅读所有评论. (2认同)