每个不可变的班级应该是最终的吗? [英] Should every immutable class be final?

查看:172
本文介绍了每个不可变的班级应该是最终的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在设计一个用于二十一点游戏的Card类。

I was designing a Card class to be used in a Blackjack game.

我的设计是使用返回的getValue()创建一个Card类,例如J为11,Q为12,K为13,然后用BlackjackCard类扩展它以覆盖该方法,使这些卡返回10。

My design was to make a Card class with a getValue() that returns, for example, 11 for J, 12 for Q and 13 for K, and then extend it with a BlackjackCard class to override that method so that those cards return 10.

然后点击我:Card类的对象应该是不可变的。所以我重新阅读Effective Java 2nd Edition,看看该做什么,我发现不可变类需要是最终的,以避免子类破坏不变性。

Then something hit me: objects of the Card class should be immutable. So I re-read Effective Java 2nd Edition to see what to do and I there I found that immutable classes need to be final, to avoid a subclass to break the immutability.

我也看过互联网,似乎每个人都同意。

I also looked in Internet and everyone seems to agree in that point.

那么Card类应该是最终的吗?

So should the Card class be final?

如何打破这个类的不变性,扩展它:

How can you break the immutability of this class, be extending it:

class Card {
  private final Rank rank;
  private final Suit suit;
  public Card(Rank rank, Suit suit) {
    this.rank = rank;
    this.suit = suit;
  }
  public Rank getRank() {
    return rank;
  }
  public Suit getSuit() {
    return suit;
  }
  public int getValue() {
    return rank.getValue();
  }
}

谢谢。

推荐答案

子类实际上不能修改其父级中 private final 属性的值,但它可能行为好像它有什么,这是 Effective Java 警告

A subclass cannot actually modify the values of private final properties in its parent, but it could behave as though it has, which is what Effective Java warns against:


确保无法扩展课程。
这可以防止粗心或恶意的
子类通过
行为来破坏类的
不可变行为好像对象的状态已经改变了

Ensure that the class can't be extended. This prevents careless or malicious subclasses from compromising the immutable behavior of the class by behaving as if the object's state has changed.

这篇关于每个不可变的班级应该是最终的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆