扩展 class 和在 Groovy 中实现特征有什么区别?

whats the difference between extending a class and implementing a trait in Groovy?

我刚刚开始使用 Groovy,我正在尝试使用特征。下面我粘贴了 www.programmingbydoing.com 的学习练习,这些练习在我开始学习 Java 时非常有用,所以我也使用 for Groovy。我完成了这个 class 然后想,为什么我不扩展 class 而不是使用特征?我很困惑,所以如果有人能提供帮助,扩展 class 和在 Groovy 中实现特征有什么区别?

  class HowOldAreYou implements AskingAndAnswering {
    /**
     *
     * @param args
     */
    static void main(args) {
        def name = AskName()
        def age = AskAge(name)
        if (age < 16)       result "You can't drive yet $name"
        if (age < 18)       result "You can't vote yet $name"
        if (age < 25)       result "You can't rent a car yet $name"
        else if (age > 25)  result "You can do anything that is legal $name"
        else                result "That's an unusual age $name!"
    }
    /**
     *
     */
    trait AskingAndAnswering {
        static def keyboard = new Scanner(System.in)
        static String AskName() {
            println "What is your name?"
            def name = keyboard.next()
        }
        static int AskAge(name) {
            println "\nOk, $name How old are you?"
            int age = keyboard.nextInt()
        }
        static void result(answer) {println "\n $answer"}
    }
}

根据规定,您只能延长一个 class。对于特性,您可以使用“实现”,类似于接口。 'implement'.

的特征数量没有限制

但是特征不同于接口,因为它包含完全实现的方法。 结果非常像组合,您可以根据需要向现有 class 添加功能,只需实现可重用特征即可。

这种行为变得非常类似于提供“多重中断”,因为您可以有效地 'extend' 具有多个特征的 class 的行为,其行为类似于基础 class.

特质并非 Groovy 所特有。这是面向对象编程中的一个概念"theory",很多语言都实现了这个概念。

"In theory",特征不是 class。它不代表"a thing",而是代表一个"capability"或一个"behavior"。它是一组提供能力的方法和状态。

这个能力可以应用到一个class("a thing"),一个class可以有多个能力(可以使用多个特征)。

在Groovy中,是class和trait的主要实际区别(当然还有traits和classes冲突的解决),但是更重要的是思考关于特征的概念,即它的技术实现。

所以,是的,如果你只有一个特质,你也许可以使用抽象 class,但你应该记住你的特质是什么。