Groovy中函数重写和可选参数的奇怪行为

时间:2017-11-17 21:32:36

标签: inheritance groovy optional-parameters optional-arguments

使用一些代码可以最好地解释这种行为。在此示例中,从类super.doSomething(t)调用y而不使用可选参数会导致它以递归方式调用自身(y.doSomething)。这是一个错误还是有一个解释为什么要离开可选参数并调用超级结果进行递归调用。

您可以在此处试用:https://docs.microsoft.com/en-us/sql/ssdt/download-sql-server-data-tools-ssdt

class x {
    void doSomething(Integer x, Boolean n=false){
        println("Super ${n}")
    }
}

class y extends x {
    @Override
    void doSomething(Integer t, Boolean q=true){
        println("Sub")
        super.doSomething(t)  //Stack overflow - super.doSomething calls the subclass
        super.doSomething(t, q)  //Works as expected
    }
}

new y().doSomething(4)

1 个答案:

答案 0 :(得分:2)

下面的代码基本上是为你所拥有的东西生成的,这个表示应该有助于理解它:

class X {
    void doSomething(Integer x) {
        // remember that for an instance of Y, this is
        // going to call doSomething(Integer, Boolean) in
        // the subclass (Y), not this class (X).
        doSomething x, false
    }

    void doSomething(Integer x, Boolean n) {
        println("Super ${n}")
    }
}

class Y extends X {
    void doSomething(Integer t) {
        doSomething t, true
    }
    @Override
    void doSomething(Integer t, Boolean q){
        println("Sub")

        // stack overflow because this calls doSomething(Integer) in
        // the parent class which is going to call
        // doSomething(Integer, Boolean), which will end up right back here
        super.doSomething(t)

        // no stack overflow
        super.doSomething(t, q)
    }
}