我开始学习 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
(这是一个抽象类,而不是匿名类)的主要优点是它定义了一种元素类型,其实例始终必须实现 incl
和 contains
,从而允许您在管理(在您的情况下)设置对象时抽象实现细节。
这一点的一个例子是,您可以将 Empty
和 NomEmpty
集合一起使用,并使用抽象类给出的约定来模糊地使用它们:
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
子类型的任何类型,即:EmptySet
或 NonEmptySet
。
这不是 Scala 或 Java 的特性,而是 OOP 的基本原则。
关于java - 在 Scala 中实现抽象类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29363767/