Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a Class Immutable

I am learning about immutable Objects. I have to make following class immutable. Did i do it right?

import java.awt.Point;
public class MyImmutablePoint {
    Point point;

    public MyImmutablePoint(Point point) {
        super();
        this.point = point;
    }

    public MyImmutablePoint() {
        this (new Point (0,0));
    }

    public Point getPoint() {
        return point;
    }

    public void setPoint(Point point) {
        this.point = point
    }
}

"Immutable" Class:

public final class MyImmutablePoint {
    private final Point point;

    public MyImmutablePoint(Point point) {
        this.point = point;
    }

    public MyImmutablePoint() {
        this (new Point (0,0));
    }

    public Point getPoint() {
        return point;
    }   
}

Iam not sure about the toString method though. and maybe returning an object like Point can be modified as well like an array but not sure

like image 522
Timo N. Avatar asked Dec 19 '22 21:12

Timo N.


2 Answers

No

final Point p = new Point(0,0);
final ImmutablePoint ip = new ImmutablePoint(p);

Two examples:

//change the original Point passed in
p.x = 10
//use the getter and change the Point
ip.getPoint().x = 10

So, first you need to create a defensive copy of the Point taken in the constructor:

public MyImmutablePoint(Point point) {
    this.point = new Point(point);
}

Then you need to create a defensive copy of the Point returned from the getter:

public Point getPoint() {
    return new Point(point);
}

This all leads me to suggest that it would probably be better not to expose the internal point at all:

public final class MyImmutablePoint {

    private final Point point;

    public MyImmutablePoint(Point point) {
        this.point = new Point(point);
    }

    public MyImmutablePoint() {
        this.point = new Point (0,0);
    }

    public int getX() {
        return point.x;
    }

    public int getY() {
        return point.y;
    }
}

Further format your code and order your members.

like image 81
Boris the Spider Avatar answered Jan 06 '23 16:01

Boris the Spider


No it is not immutable. Point can still be modified by the creator of MyImmutablePoint. Ex:

    Point point = new Point(1, 1);
    MyImmutablePoint immutablePoint = new MyImmutablePoint(point);
    point.setLocation(0, 0);
like image 22
why_vincent Avatar answered Jan 06 '23 17:01

why_vincent