为什么是“抽象覆盖"?不需要“覆盖"独自在亚底? [英] Why is "abstract override" required not "override" alone in subtrait?

查看:30
本文介绍了为什么是“抽象覆盖"?不需要“覆盖"独自在亚底?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了 Scala 编程的部分,其中 abstract override 是介绍,但我仍然对这些修饰符的加入究竟意味着什么感到困惑.使用这些修饰符的代码片段粘贴在下面:

I read the section of Programming in Scala where abstract override is introduced, but I'm still confused by what exactly is signified by the joining of these modifiers. The snippet of code in which these modifiers is used is pasted below:

trait Doubling extends IntQueue {
    abstract override def put(x: Int) { super.put(2 * x) }
}

特别是,在这种情况下,我对 abstract 的目的感到困惑,以及为什么我们不能简单地使用 override 关键字来达到预期的结果.如果我们不包括对super 的调用,我们是否需要关键字abstract?为什么或者为什么不?我正在寻找有关此关键字组合的详细说明,因为它与可堆叠特征有关.

In particular, I am confused by the purpose of abstract in this case, and why we cannot achieve the expected results simply with the override keyword. If we did not include a call to super, would we need the keyword abstract? Why or why not? I'm looking for a detailed explanation of this keyword combo as it pertains to stackable traits.

推荐答案

原因是基类方法是抽象

The reason is that the base class method is abstract

abstract class IntQueue {
  def get(): Int
  def put(x: Int)
}

如果你不把 abstract 放在特征上,你最终会得到你想要的解释:

If you were to not put abstract on the trait you end up with the explanation you were seeking:

trait Doubling extends IntQueue {
     override def put(x: Int) { super.put(2 * x) }
}
<console>:9: error: method put in class IntQueue is accessed from
 super. It may not be abstract unless it is overridden by a member 
 declared `abstract' and `override'
            override def put(x: Int) { super.put(2 * x) }

所以 - 您需要将该方法标记为 abstract.

So - you would need to mark the method as abstract.

这是等式的另一面":如果方法确实有实现,则不必将trait的方法标记为abstract:

Here is the "other side" of the equation: if the methods do have implementations then it is not necessary to mark the trait's method as abstract:

 abstract class IntQueue {
    import collection.mutable._
        val q  =  Queue[Int]()
      def get(): Int = { q.dequeue() }
      def put(x: Int) = { q.enqueue(x) }
   }

现在不需要包含abstract

 trait Doubling extends IntQueue {
        /* Look Ma! no abstract here ! */   override def put(x: Int) { super.put(2 * x) }
      }
defined trait Doubling

这篇关于为什么是“抽象覆盖"?不需要“覆盖"独自在亚底?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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