java - 在 Scala 中实现抽象类

标签 java scala oop abstract-class

我开始学习 Scala 编程和 OOP 编程。 我不明白抽象类的概念。我读过这个例子:

Consider the task of writing a class for sets of integer numbers with two operations,incl and contains. (s incl x) should return a new set which contains the element x together with all the elements of set s. (s contains x) should return true if the set s contains the element x, and should return false otherwise. The interface of such sets is given by:

abstract class IntSet {
  def incl(x: Int): IntSet
  def contains(x: Int): Boolean
}

Let’s say, we plan to implement sets as binary trees. There are two possible forms of trees. A tree for the empty set, and a tree consisting of an integer and two subtrees. Here are their implementations.

class EmptySet extends IntSet {
  def contains(x: Int): Boolean = false
  def incl(x: Int): IntSet = new NonEmptySet(x, new EmptySet, new EmptySet)
}



class NonEmptySet(elem: Int, left: IntSet, right: IntSet) extends IntSet { 
  def contains(x: Int): Boolean =
    if (x < elem) left contains x
    else if (x > elem) right contains x else true
  def incl(x: Int): IntSet =
    if (x < elem) new NonEmptySet(elem, left incl x, right)
    else if (x > elem) new NonEmptySet(elem, left, right incl x) 
    else this
}

Both EmptySet and NonEmptySet extend class IntSet. This implies that types EmptySet and NonEmptySet conform to type IntSet – a value of type EmptySet or NonEmptySet may be used wherever a value of type IntSet is required.

我不清楚为什么引入匿名类是有用的,因为在扩展匿名类的两个类中再次有 incl 和 contains 的定义。

谢谢!

最佳答案

使用 InClass (这是一个抽象类,而不是匿名类)的主要优点是它定义了一种元素类型,其实例始终必须实现 inclcontains ,从而允许您在管理(在您的情况下)设置对象时抽象实现细节。

这一点的一个例子是,您可以将 EmptyNomEmpty 集合一起使用,并使用抽象类给出的约定来模糊地使用它们:

val l = List[IntSet](new EmptySet, new NomEmptySet(1, new EmptySet, new EmptySet)
val setsContainingThree = l.filter(_.contains(3))

您的代码利用了这一点,请注意,我编写了 new NomEmptySet(1, new EmptySet, new EmptySet) 但它也可能是:

new NomEmptySet(1, new EmptySet, new NomEmptySet(2, new EmptySet, new EmptySet))

您的 NonEmptySet 构造函数需要 InSet,因此您的实际参数可以是 InSet 子类型的任何类型,即:EmptySetNonEmptySet

这不是 Scala 或 Java 的特性,而是 OOP 的基本原则。

关于java - 在 Scala 中实现抽象类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29363767/

相关文章:

java - 如何在应用程序中正确运行自定义 Groovy 脚本?

java - 从 repo 构建可部署的 maven 代码的常规工作流程

java - Scala 中 java.util.Comparator 的通用实现

iphone - 编写可重用接口(interface)对象的正确技术?

oop - Go 结构中的 omitempty 用例有哪些?

java.lang.IllegalArgumentException : argument type mismatch:when store the form values in Database 异常

java - 使用 x509 正确配置 Azure IoT 中心 DPS 组注册

parsing - 从使用 Scala Parser Combinators 编写的解析器返回有意义的错误消息

scala - Play Framework 双向支持,包括旧版浏览器

java - 使用 While 与 If 防止数组中出现重复的整数 ID 号