Dmytro
Dmytro

Reputation: 2009

Immutable non-final classes

Is a class still considered as immutable if it can be subclassed(but other rules are kept)? For example:

abstract class Figure {
abstract double area();
}

class Rectangle extends Figure {
private final double length;
private final double width;

Rectangle(double length, double width) {
    this.length = length;
    this.width = width;
} 

double area() { return length * width; }
}

Is it immutable?

Upvotes: 2

Views: 151

Answers (3)

fge
fge

Reputation: 121710

Immutable non-final classes

do not exist.

If your class is not final, it can be subclassed.

By definition, an immutable class only has invariants. But if it is not final, you can subclass it and introduce instance fields which are NOT invariants. So:

public class A 
{
    private final int a;

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

is NOT immutable, since you can:

public class B
    extends A
{
    // NOT AN INVARIANT
    private int b;

    public B(final int a)
    {
        super(a);
    }

    public void setNonInvariant(final int b)
    {
        this.b = b;
    }
}

HOWEVER: class A is thread safe. But it is not immutable. And class B is not thread safe...

Upvotes: 1

Martin Seeler
Martin Seeler

Reputation: 6982

The fields length and width are still immutable for all subclasses (if they are not shadowed by the subclasses fields with the same name).

But a subclass can define it's own mutable fields.

So the answer is: it depends.

If you do not inherit other classes of Rectangle with mutable fields, than the answer is yes. Otherwise no.

Upvotes: 2

tddmonkey
tddmonkey

Reputation: 21184

If the base class itself is immutable in your example then yes, this is immutable. In a language such as Java that doesn't support compiler enforced immutability it falls on to you as the developer to handle it- and what means basically is that any object that cannot have its state changed is considered immutable.

In your example above you don't even need to make your variables final - the fact that nothing can change them means it's immutable.

Upvotes: 0

Related Questions