groovy protected属性不能在子类中重写

时间:2011-08-27 00:26:14

标签: groovy

子类调用父受保护的方法,它期望返回受保护的覆盖属性。 但要归还父母的财产。

//父类:

package tz

import java.util.List;

class AbstractController {
    protected List keywordFilter = []
    protected String methodKey(){
        return "\t[method]parent,$keywordFilter,"+keywordFilter.toString()
    }
    def closureKey(){
        return "\t[closure]parent,$keywordFilter,"+keywordFilter.toString()
    }
}

//亚类:

package tz

import java.util.List;

class SubController extends AbstractController{
    protected List keywordFilter = ['a']
    public SubController(){
    }

    public void test(){
        println "subCall:"+methodKey()+closureKey()
    }
    def test2 = {
        println "c,$keywordFilter,"+methodKey()+closureKey()
    }

    public static void main(String[] args) {
        def s = new SubController()
        s.test()
        s.test2()
    }
}

//输出:

subCall:[method]parent,[],[]    [closure]parent,[],[]
c,[a],  [method]parent,[],[]    [closure]parent,[],[]

1 个答案:

答案 0 :(得分:8)

在Java和Groovy中,子类中的字段不会被覆盖。基类版本只是由子类版本隐藏。实际上,您在类中获得了两个具有相同名称的字段。基类方法将看到基类字段和子类方法将看到子类字段。

解决方案通常是将字段包装在getter方法中。在groovy:

class AbstractController {
    protected List getKeywordFilter() { [] }
    ...
}
class SubController extends AbstractController {
    protected List getKeywordFilter() { ['a'] }
    ...
}

遵循groovy属性约定,您仍然可以将其引用为"$keywordFilter",它将自动调用getter。

相关问题