简体   繁体   English

不可变的非最终课程

[英]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? 它是不可变的吗?

The fields length and width are still immutable for all subclasses (if they are not shadowed by the subclasses fields with the same name). 对于所有子类,字段lengthwidth仍然是不可变的(如果它们没有被具有相同名称的子类字段遮蔽)。

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. 如果你没有使用可变字段继承其他类的Rectangle ,那么答案是肯定的。 Otherwise no. 否则没有。

Immutable non-final classes 不可变的非最终课程

do not exist. 不存在。

If your class is not final , it can be subclassed. 如果您的课程不是final ,则可以将其分类。

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. 但是如果它不是final ,你可以对它进行子类化并引入非变量的实例字段。 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 . 但是: A类是线程安全的 But it is not immutable. 但这不是一成不变的。 And class B is not thread safe... B类不是线程安全的......

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. 在诸如Java之类的不支持编译器强制不变性的语言中,它作为开发人员来处理它 - 并且基本上意味着任何不能将其状态改变的对象被认为是不可变的。

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. 在上面的例子中,你甚至不需要让你的变量最终 - 事实上没有任何东西可以改变它们意味着它是不可变的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM